获取NodeJS中Mongo数据库中插入文档的_id [英] Get the _id of inserted document in Mongo database in NodeJS

查看:122
本文介绍了获取NodeJS中Mongo数据库中插入文档的_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用NodeJS在MongoDB中插入文档。使用 collection.insert 我可以将文档插入数据库,如下代码所示:

I use NodeJS to insert documents in MongoDB. Using collection.insert I can insert a document into database like in this code:

// ...
collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId; // = ???
});
// ...

如何获得 _id 插入对象?

有没有办法获得 _id 而无需获取最新信息对象插入 _id

Is there any way to get the _id without getting latest object inserted _id?

假设同时很多人访问数据库,我不能确保最新的id是插入对象的id。

Supposing that in same time a lot of people access the database, I can't be sure that the latest id is the id of object inserted.

推荐答案

<$ c $的回调还有第二个参数c> collection.insert 将返回插入的文档或文档,其中应包含_ids。

There is a second parameter for the callback for collection.insert that will return the doc or docs inserted, which should have _ids.

尝试:

collection.insert(objectToInsert, function(err,docsInserted){
    console.log(docsInserted);
});

并检查控制台以了解我的意思。

and check the console to see what I mean.

这篇关于获取NodeJS中Mongo数据库中插入文档的_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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