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