2013-12-10 29 views
2

因此,在節點中我有這個代碼,這是完全微不足道的......但它不工作。僧侶發現返回奇怪的json

var collection = db.get('fisforfriends'); 
var db = monk('localholst:27017/fisforfriends'); 
... 
var userName = req.body.username; 

上面的插入工作。只是向你們展示=)!

console.log(collection.find({}, {username: userName})); 

在底部打印大量文本。

該元素在數據庫中不存在,但我添加元素的函數有一天工作,所以我不擔心這一點。如果不存在,該功能會添加它。

我所擁有的只是打印所有這些的console.log調用。我希望能讓它印出'假'或其他東西。

9 Dec 22:54:27 - [nodemon] starting `node app.js` 
Express server listening on port 3000 
GET/200 319ms - 427b 
GET /stylesheets/style.css 304 4ms 
{ col: 
    { manager: 
     { driver: [Object], 
     collections: [Object], 
     options: [Object], 
     _events: {} }, 
    driver: 
     { emitter: [Object], 
     state: 0, 
     _dbconn: [Object], 
     db: null, 
     username: '', 
     password: undefined, 
     admin: [Object], 
     _collections: [Object], 
     bson_serializer: [Object], 
     ObjectID: [Object] }, 
    name: 'fisforfriends', 
    col: 
     { emitter: [Object], 
     state: 0, 
     options: undefined, 
     skinDb: [Object], 
     ObjectID: [Object], 
     collectionName: 'fisforfriends', 
     collection: null, 
     internalHint: null, 
     hint: [Getter/Setter] }, 
    options: {} }, 
    type: 'find', 
    completed: false, 
    opts: { username: 'fa', fields: {}, safe: true }, 
    _events: 
    { error: { [Function: g] listener: [Function] }, 
    success: { [Function: g] listener: [Function] } }, 
    fulfill: [Function], 
    query: {} } 
9 Dec 22:54:45 - [nodemon] restarting due to changes... 
9 Dec 22:54:45 - [nodemon] C:\Users\hassan\Documents\Hassans_Bravery\fisforfrien 
ds\routes\index.js 
+0

看起來好像是對我的承諾 – pfried

+0

查看[documentation](https://npmjs.org/package/monk),其給出的所有執行異步操作的方法都會返回一個promise。 – user568109

回答

1

正如我建議以上這不是從該數據庫中的對象是當它已完成執行

數據庫調用幾乎八方異步和特別是在節點的情況下,將返回該對象的許.js是事件驅動的。這意味着需要時間,但您的console.log立即執行。結果不會在那裏。

如果我看一看的文檔,第二個參數是回調函數傳遞中,將檢索對象從查詢

所以,你可以做

users.find({}).on('success', function (doc) { /* doc is the result available here */ }); 

users.find({}, function (err, docs){ /* doc is the result available here */ });