Node.js / Mongodb插入callback返回undefined
当我运行下面的简单代码插入一个新的文档:
collectionUsers.insert({'name':'john'},function(err,records){ if (err) throw err; console.log("Id of new document added = " + records[0]._id); });
我得到以下错误:
catch(err) { process.nextTick(function() { throw err}); } ^ TypeError: Cannot read property '_id' of undefined
callback函数没有返回数组吗? 我只是试图获取新文档的ID,并将其保存在一个variables,以备将来使用。 谢谢你的帮助。
另外,如果我使用insertOne,我得到这个输出:添加新文档的ID = {“ok”:1,“n”:1}
但我想用插入…
在包含插入的文档/文档的records
有ops
对象。
尝试:
collectionUsers.insert({'name':'john'},function(err,records){ // You can explore more here console.log("record contents",JSON.stringify(records,null,4)); // Desired output console.log("Id of new document added = " + records.ops[0]._id); });
非常感谢user2285490和robertklep。 我终于意识到logging中的操作对象是什么。 这是未来引用的api文档:
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#~insertWriteOpCallback