MongoDB,迭代游标时出现问题



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

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');
      }
});

您应该始终检查记录是否正确插入而没有任何错误。为此,必须将回调传递给插入方法。像这样:

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 参数将返回在您的集合中成功编写的文档。因此,您可以直接将它们记录到控制台,如上例所示。

最新更新