【问题标题】:Can we use callbacks in the mongo shell?我们可以在 mongo shell 中使用回调吗?
【发布时间】:2019-05-08 15:26:00
【问题描述】:

我想在collection1 中插入一个文档,在成功插入文档后,我想在collection2 中插入另一个文档。 collection2 中文档的字段之一将是刚刚插入到collection1 中的文档的_id

我正在使用回调:

db.collection1.insert(<document>,function(err,doc)){
     db.collection2.insert({collection1_id: doc[0]._id, <field>:<value>})

但是,如果没有Node.js,似乎回调不可用。

有什么解决办法吗?

【问题讨论】:

  • 没有node.js是什么意思?在 Mongo shell 中?
  • @estus,是的,在 mongo shell 中或只是在命令行中

标签: mongodb mongo-shell


【解决方案1】:

回调是 Node.js 异步 API 的一部分,在 mongo shell(如 MongoDB 4.0)中不受支持。但是,您始终可以编写没有回调的等价物。

mongo shell 的insertOne() 方法将返回一个insertedId 字段,其中包含插入文档的_id 值,因此您可以保存或引用该值。

例如:

db.collection2.insertOne({
    collection1_id: db.collection1.insertOne({}).insertedId,
    field: 'value'
})

【讨论】:

  • 如何实际使用这个值?
  • @user1767316 答案中有一个示例,引用 insertedId 获取新文档:db.collection1.insertOne({}).insertedId。如果这不是您要查找的内容,我建议您提出一个包含相关详细信息的新问题。
猜你喜欢
  • 2013-03-25
  • 2011-05-20
  • 2015-10-11
  • 2013-06-14
  • 2016-08-26
  • 1970-01-01
  • 2016-05-23
  • 2018-01-24
相关资源
最近更新 更多