如何获得集合的最后分配的对象ID

问题描述 投票:0回答:1

我有2个集合,一个集合用于存储代理程序详细信息,例如名称和代理程序类型..etc,另一个集合用于存储用户凭证详细信息,例如user_name和密码。

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

现在我想在插入新记录时将ObjectIdagent_collectionuser_collection作为agent_id的值。是否有任何方法可用于获取集合的ObjectId

谢谢

node.js angularjs mongodb mean-stack
1个回答
0
投票

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

回调是insertOneWriteOpCallback(error, result)类型,其中resultinsertOneWriteOpResult对象。 result对象具有insertedId字段;这是“驱动程序为插入操作生成的ObjectId。”。

因此,您的代码可以是:

  let new_agent_doc = { agent_name: 'John Doe', email: '[email protected]' }

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

      console.log('inserted the following ID: ', result.insertedId);
      // use the newly created agent's id value: result.insertedId
  });
© www.soinside.com 2019 - 2024. All rights reserved.