如何获取集合的最后分配的 objectID

How get last assigned objectID of collection

我有 2 个集合,一个用于存储代理详细信息,如姓名和代理类型等,另一个用于存储用户凭据详细信息,如 user_name 和密码

agent_collection{
   _id:''
   NAME:'',
   MAIL:''
}
user collection{
_id:'',
agent_id:'',
user_name:'',
password:''
}

现在我想要 user_collectionagent_collectionObjectId 作为 agent_id 的值,同时插入新的 record.is 有任何方法可用于获取集合的 ObjectId

谢谢

insert 方法的形式为:insertOne(doc, options, callback)

回调的类型为 insertOneWriteOpCallback(error, result),其中 result 是一个 insertOneWriteOpResult 对象。 result 对象有一个 insertedId 字段;这是 "The driver generated ObjectId for the insert operation.".

因此,您的代码可以是:

  let new_agent_doc = { agent_name: 'John Doe', email: 'johnd@example.com' }

  collection.insertOne(doc, (err, result) => {

      console.log('inserted the following ID: ', result.insertedId);
      // use the newly created agent's id value: result.insertedId
  });