2016-02-28 14 views
0

我无法理解为什么插入的MongoDB文档虽然包含项目,但代码无法迭代。游标对象本身不是null。我能够检索使用db.newmongo.find()MongoDB,在遍历游标时发生问题

var url = 'mongodb://localhost:27017/test'; 
MongoClient.connect(url, function(err, db) { 
db.collection("newmongo").insert([{"name": "XXX", "age": "50"}, 
        {"name": "YYY", "age": 43}, 
        {"name": "ZZZ", "age": 27}, 
        {"name": "AAA", "age": 29}, 
        {"name": "BBB", "age": 34}]); 

console.log("Connected correctly to server."); 
var cursor=db.collection('newmongo').find(); 
console.log(cursor); // This gets logged 
cursor.each(function(err, doc) {  
     if (doc != null) { 
     console.log('Document found'); 
     } else { 
     console.log('Document not found'); 
     } 
}); 
+1

为什么它是重复的?因为另一个使用像'.insert()'这样的异步调用的人是在之后立即尝试寻找那个结果,**没有**“将该操作**后面的代码放入该操作的回调中”。您正在使用具有异步功能的同步编码技术。理解这些调用不会阻塞,直到完成以下代码行的运行。回调。 –

+0

看起来你在尝试插入的JSON文档中有错误 –

回答

1

您应经常检查,如果记录被正确插入没有任何错误的文件。为此,您必须将回调传递给insert方法。事情是这样的:

var url = 'mongodb://localhost:27017/test'; 
MongoClient.connect(url, function(err, db) { 
if(err){ 
    console.log("Error connecting to MongoDB"); 
    return; 
} 
console.log("Connected correctly to server."); 
db.collection("newmongo").insert([{name: "XXX", age: 50}, 
       {name: "YYY", age: 43}, 
       {name: "ZZZ", age: 27}, 
       {name: "AAA", age: 29}, 
       {name: "BBB", age: 34}], function(err, docs){ 
    if(err){ 
     console.log("Error inserting documents in MongoDB : " + JSON.stringify(err)); 
    } 
    if(docs){ 
     console.log("Following Documents were Successfully Inserted : \n" + JSON.stringify(docs)); 
    } 
}); 

此外,由于这是一个async电话,也不会等到文件完成插入,并将火find瞬间。因此,当写入操作仍在进行中时,您可能无法获得newmongo集合中的任何记录。

所以我建议只有在if(docs)的条件后才拨打find

而且我也认为调用find不是必需的,因为在回调中返回的参数docs将返回成功写入集合的文档。因此,您可以直接将它们记录到控制台,如上例所示。