获取 NodeJS 中 Mongo 数据库中插入文档_id

2022-08-30 05:20:02

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

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

如何获取插入对象?_id

有没有办法在不插入最新对象的情况下获取 ?_id_id

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


答案 1

比使用第二个参数进行回调更短的方法是使用返回(在回调函数内部,假设它是一个成功的操作)。collection.insertobjectToInsert._id_id

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

答案 2

回调有第二个参数,它将返回插入的一个或多个文档,该参数应具有_ids。collection.insert

尝试:

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

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