我们可以在 mongo shell 中使用回调吗?

Can we use callbacks in the mongo shell?

我想在 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 异步 API 的一部分,在 mongo shell 中不受支持(截至 MongoDB 4.0)。但是,您始终可以编写不带回调的等价物。

mongo shell 的 insertOne() 方法将 return 一个 insertedId 字段与插入文档的 _id 值,因此您可以保存或引用此值。

例如:

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