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

Ion*_*zău 92 javascript mongodb node.js

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

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

如何获取_id插入的对象?

有没有办法让_id没有插入最新的对象_id

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

geo*_*yer 84

回调的第二个参数collection.insert将返回插入的doc或docs,它应该有_ids.

尝试:

collection.insert(objectToInsert, function(err,docsInserted){
    console.log(docsInserted);
});
Run Code Online (Sandbox Code Playgroud)

并检查控制台,看看我的意思.

  • 回调实际上返回插入的文档数组.因此,如果您插入了单个文档,则可以访问插入的记录,如下所示.collection.insert({name:"David",title:"About MongoDB"},function(err,records){console.log("Record added as as"+ records [0] ._ id);}); 参考:http://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html (4认同)
  • docsInserted不会为我返回_id.它为我返回{"ok":1,"n":1,"opTime":{"ts":"6361004504208375809","t":5},"electionId":"7fffffff0000000000000005"} (4认同)
  • Callbacks API已更改:http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#~WriteOpResult (2认同)

Ion*_*zău 82

比使用第二个参数更短的方法collection.insert是使用objectToInsert._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
});
Run Code Online (Sandbox Code Playgroud)

  • 很有见地谢谢你.自回调参数更改以来,无法在其他任何位置找到此信息. (4认同)
  • @AndyLorenz什么是`objectInserted`?我猜你错过了这个答案:Mongo驱动程序将`_id`字段附加到原始对象.我编辑了答案,到处都使用`objectToInsert`.希望现在的事情更清楚了.:) (3认同)
  • 注意:不推荐使用`insert()`。使用 `insertOne()` 代替 (2认同)

Ser*_*ice 16

正如ktretyak所说,获取插入文档的ID最好的方法是在结果对象上使用insertedId属性.在我的情况下result._id没有工作,所以我不得不使用以下:

db.collection("collection-name")
  .insertOne(document)
  .then(result => {
    console.log(result.insertedId);
  })
  .catch(err => {
    // handle error
  });
Run Code Online (Sandbox Code Playgroud)

如果你使用回调也是一样的.


Sid*_*dak 11

我实际上为insert的回调函数中的第二个参数做了一个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
       }
});
Run Code Online (Sandbox Code Playgroud)

  • 这会输出一个 `ObjectID {_bsontype: "ObjectID", id: Buffer(12)}`。我如何使用它来获取数据库中的实际 id?...在​​另一条评论中找到了答案:使用 `result.insertedId.toString() ` (2认同)

bey*_*ski 9

您可以使用异步函数自动获取 _id 字段,而无需操作数据对象:

\n
async function save() {\n  const data = {\n    name: "John"\n  }\n\n  await db.collection('users').insertOne(data)\n\n  return data\n}\n
Run Code Online (Sandbox Code Playgroud)\n

返回(data对象):

\n
\n

{
\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0_id: '5dbff150b407cc129ab571ca',
\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0name: '约翰',
\n}

\n
\n


Sau*_*tel 6

Mongo将完整的文档作为回调对象发送,因此您只需从那里获取它.

例如

collection.save(function(err,room){
  var newRoomId = room._id;
  });
Run Code Online (Sandbox Code Playgroud)


ktr*_*yak 6

现在您可以使用insertOne方法并在 promise 的 result.insertedId 中


Ham*_*RIM 6

如果您想使用“_id”,请使用 simpley

result.insertedId.toString() 
Run Code Online (Sandbox Code Playgroud)

// toString 将从十六进制转换

  • 是的,肯定有版本更改,因为其他答案没有提到 `result.insertedId` 是一个 `ObjectID` 类型对象。`.toString()` 会将此对象转换为真正的 UUID。 (2认同)