在NodeJS中获取Mongo数据库中插入文档的_id [英] Get the _id of inserted document in Mongo database in NodeJS
问题描述
我使用 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.
推荐答案
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屋!