如何在一个查询中更新两个集合?



我有两个模型一个是具有此属性的产品

const mongoose = require("mongoose");
const salesSchema =new mongoose.Schema({
productname:{
type:String,
required:trud,
unique:true
},
productCount:{
type:Number,
required:true
}
});
module.exports = mongoose.model("products",salesSchema);

和sales的属性

const mongoose = require("mongoose");
const salesSchema =new mongoose.Schema({
productId:{
type:mongoose.Schema.Types.ObjectId,
ref:"products",
},
salesCount:{
type:Number,
required:true
}
});
module.exports = mongoose.model("sales",salesSchema);

当有人处理销售时,它应该减少或增加自动更新计数产品表。

在任何给定时间只能对一个集合运行查询。所以你必须分开做那些查询。但是,如果您使用MongoDB Atlas进行托管,则可以使用它们的Trigger功能来侦听销售集合的更改。当插入操作被触发时,对需要减少数量的产品运行查询。

如果你不使用Atlas,你可以使用MongoDB通过Node SDK可用的更改流做同样的事情作为触发器,监听插入到特定集合。(您可以在任何环境中执行此操作,但是您需要配置一个Replica Set以使其工作)

所以我说的是;只插入销售文档,然后让一个观察者处理产品集合更新。

const changeStream = salesSchema.collection.watch([{
$match: {
operationType: 'insert',
},
}], {
fullDocument: 'updateLookup',
})
changeStream.on('change', changeEvent => {
const salesDocument = changeEvent.fullDocument
// Run the product update here
})