我想在collection1
中插入一个文档,在成功插入文档之后,我想在collection2
中插入另一个文档。collection2
中文档的一个字段是刚刚插入到collection1
中的文档的_id
。
我正在使用回调:
db.collection1.insert(<document>,function(err,doc)){
db.collection2.insert({collection1_id: doc[0]._id, <field>:<value>})
但是,似乎没有Node.js
回调是不可用的。
有什么变通方法吗?
发布于 2019-05-09 10:02:41
回调是Node.js异步API的一部分,在mongo
外壳中不受支持(在MongoDB 4.0中)。但是,您始终可以在没有回调的情况下编写等效的代码。
mongo
外壳的insertOne()
方法将返回一个insertedId
字段,其中包含所插入文档的_id
值,因此您可以保存或引用此值。
例如:
db.collection2.insertOne({
collection1_id: db.collection1.insertOne({}).insertedId,
field: 'value'
})
https://stackoverflow.com/questions/56044146
复制相似问题