【问题标题】:How get last assigned objectID of collection如何获取集合的最后分配的objectID
【发布时间】:2020-06-26 19:09:51
【问题描述】:

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

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

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

谢谢

【问题讨论】:

标签: node.js angularjs mongodb mean-stack


【解决方案1】:

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

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

所以,你的代码可以是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    相关资源
    最近更新 更多