Javascript 在NodeJS中获取Mongo数据库中插入文档的_id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14481521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the _id of inserted document in Mongo database in NodeJS
提问by Ionic? Biz?u
I use NodeJS to insert documents in MongoDB. Using collection.insertI can insert a document into database like in this code:
我使用 NodeJS 在 MongoDB 中插入文档。使用collection.insert我可以将文档插入数据库,如以下代码所示:
// ...
collection.insert(objectToInsert, function(err){
if (err) return;
// Object inserted successfully.
var objectId; // = ???
});
// ...
How can I get the _idof inserted object?
我怎样才能得到_id插入的对象?
Is there any way to get the _idwithout 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.
假设同时有很多人访问数据库,我不能确定最新的id是插入的对象的id。
采纳答案by georgedyer
There is a second parameter for the callback for collection.insertthat will return the doc or docs inserted, which should have _ids.
回调的第二个参数collection.insert将返回插入的文档或文档,其中应该有 _ids。
Try:
尝试:
collection.insert(objectToInsert, function(err,docsInserted){
console.log(docsInserted);
});
and check the console to see what I mean.
并检查控制台以了解我的意思。
回答by Ionic? Biz?u
A shorter way than using second parameter for the callback of collection.insertwould be using objectToInsert._idthat returns the _id(inside of the callback function, supposing it was a successful operation).
比使用第二个参数用于回调更短的方法collection.insert是使用objectToInsert._id返回_id(在回调函数内部,假设它是一个成功的操作)。
The Mongo driver for NodeJS appends the _idfield to the original object reference, so it's easy to get the inserted id using the original object:
NodeJS 的 Mongo 驱动程序将_id字段附加到原始对象引用,因此很容易使用原始对象获取插入的 id:
collection.insert(objectToInsert, function(err){
if (err) return;
// Object inserted successfully.
var objectId = objectToInsert._id; // this will return the id of object inserted
});
回答by Serjuice
As ktretyak said, to get inserted document's ID best way is to use insertedId property on result object. In my case result._id didn't work so I had to use following:
正如 ktretyak 所说,获取插入文档的 ID 的最佳方法是在结果对象上使用 insertId 属性。在我的情况下 result._id 不起作用,所以我不得不使用以下内容:
db.collection("collection-name")
.insertOne(document)
.then(result => {
console.log(result.insertedId);
})
.catch(err => {
// handle error
});
It's the same thing if you use callbacks.
如果你使用回调也是一样的。
回答by Sidak
I actually did a console.log() for the second parameter in the callback function for insert. There is actually a lot of information returned apart from the inserted object itself. So the code below explains how you can access it's id.
我实际上为插入的回调函数中的第二个参数做了一个 console.log() 。除了插入的对象本身之外,实际上还有很多信息返回。所以下面的代码解释了如何访问它的 id。
collection.insert(objToInsert, function (err, result){
if(err)console.log(err);
else {
console.log(result["ops"][0]["_id"]);
// The above statement will output the id of the
// inserted object
}
});
回答by Saurabh Chandra Patel
Mongo sends the complete document as a callbackobject so you can simply get it from there only.
Mongo 将完整文档作为回调对象发送,因此您只能从那里获取它。
for example
例如
collection.save(function(err,room){
var newRoomId = room._id;
});
回答by ktretyak
回答by Pyae Sone
@JSideris, sample code for getting insertedId.
@JSideris,获取insertId 的示例代码。
db.collection(COLLECTION).insertOne(data, (err, result) => {
if (err)
return err;
else
return result.insertedId;
});
回答by Hamit YILDIRIM
if you want to take "_id" use simpley
如果您想使用“_id”,请使用 simpley
result.insertedId.toString()
// toString will convert from hex
// toString 将从十六进制转换
回答by beytarovski
You could use async functionsto get _id field automatically without manipulating data object:
您可以使用异步函数自动获取 _id 字段而无需操作数据对象:
async function save() {
const data = {
name: "John"
}
await db.collection('users', data )
return data
}
Returns data:
返回数据:
{
_id: '5dbff150b407cc129ab571ca',
name: 'John'
}

