2015-11-04 81 views
0

我在试图成功查询Mongo的墙上敲打我的头。如何在Mongo中查询?

此代码:

async.waterfall([ 
     function(callback){ 
      cursor = db.collection(collection).findOne(query) 
      callback(null); 
     }, 
     function(callback){ 
      console.log("Result is:" + cursor); 
      console.log(JSON.stringify(cursor)); 
      callback(null); 
     } 
    ]); 

产生以下输出:

result is:[object Object] 
{} 

为什么?有一份文件应该在收集中找到。

作为后续问题,我怎么能看到什么

[object Object] 

是什么?

+0

尝试'“的结果是:” cursor'而不将正常登录。您应该将查询结果传递给回调函数而不是光标。即在回调函数'.findOne'中使用'callback'。这是本地MongoDB驱动程序吗?什么版本? –

+0

我正在使用Mongo v 3.0。请您用不同的词语来解释/说出:“您应该将查询结果传递给回调函数而不是光标,即在回调函数中使用.findOne回调函数”。谢谢! (另外:“结果是:”,光标更改只是打印{}。) – Dirk

回答

4

基本上你应该等待查询完成,然后调用回调,并期望任何结果:

 async.waterfall([ 
      function(callback){ 
       db.collection(collection).findOne(query, function(err, result) { 
        callback(err, result); // if there is no err, it will be null 
       }); 
       // the above can be simplified to just          
       // db.collection(collection).findOne(query, callback); 
       // since findOne callback and current function callback have the same arguments 
      }, 
      function(result, callback) { 
       // use comma here to automatically doing JSON.stringiry(result) 
       console.log("Result is:", result); 
       callback(); 
      } 
     ], function(err) { 
      // here is your final callback where you know that async.waterfall 
      // is finished (with or without error) 
     });