Vid*_*ain 0 mongoose mongodb node.js mongoose-schema
我一直在尝试updatemany与猫鼬一起使用。我想使用对象数组更新数据库中的值。
[
{
"variantId": "5e1760fbdfaf28038242d676",
"quantity": 5
},
{
"variantId": "5e17e67b73a34d53160c7252",
"quantity": 13
}
]
Run Code Online (Sandbox Code Playgroud)
我想使用 variantId 作为过滤器。模型架构是:
let variantSchema = new mongoose.Schema({
variantName: String,
stocks: {
type: Number,
min: 0
},
regularPrice: {
type: Number,
required: true
},
salePrice: {
type: Number,
required: true
}
})
Run Code Online (Sandbox Code Playgroud)
我想使用 variantId 过滤模型,然后减少库存。
由于您需要使用多个条件更新多个文档,.updateMany()因此将不起作用 - 只有当您需要更新具有相同值的多个文档时,它才会起作用,请尝试以下查询,这将帮助您在一次数据库调用中完成它:
const Mongoose = require("mongoose");
let variantSchema = new mongoose.Schema({
variantName: String,
stocks: {
type: Number,
min: 0
},
regularPrice: {
type: Number,
required: true
},
salePrice: {
type: Number,
required: true
}
})
const Variant = mongoose.model('variant', variantSchema, 'variant');
let input = [
{
"variantId": "5e1760fbdfaf28038242d676",
"quantity": 5
},
{
"variantId": "5e17e67b73a34d53160c7252",
"quantity": 13
}
]
let bulkArr = [];
for (const i of input) {
bulkArr.push({
updateOne: {
"filter": { "_id": Mongoose.Types.ObjectId(i.variantId) },
"update": { $inc: { "stocks": - i.quantity } }
}
})
}
Variant.bulkWrite(bulkArr)
Run Code Online (Sandbox Code Playgroud)