Node.js/Mongodb插入回调返回未定义 [英] Node.js / Mongodb insert callback returning undefined

查看:134
本文介绍了Node.js/Mongodb插入回调返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行下面的简单代码以插入新文档时:

when I run the simple code below to insert a new document:

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

回调函数不返回数组吗?我只是想获取新文档的ID,并将其保存在变量中以备将来使用.感谢您的帮助.

Doesn't the callback function return an array? I'm just trying to get the id of the new document and save it in a variable for future use. Thanks for your help.

或者,如果我改用insertOne,则会得到以下输出: 添加的新文档ID = {"ok":1,"n":1}

Alternatively, if I use insertOne instead, I get this output: Id of new document added = {"ok":1,"n":1}

但是我想使用插入...

But I want to use insert...

推荐答案

records中有一个ops对象,其中包含插入的doc/docs.

There is ops object in records which contains inserted doc/docs.

尝试:

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

这篇关于Node.js/Mongodb插入回调返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆