猫鼬更新查询超过最小值



我有产品和交易模型。如果用户进行交易,它应该将他的订单数量减去产品。但是,如果交易数量高于产品的最小设置,则仍会继续进行。使产品的数量为负


router.route("/add").post(async (req, res) => {
const { f_name, l_name, order } = req.body;
try {
const newTransaction = new Transaction({
f_name,
l_name,
order,
});
for (const product of order) {
let newProduct = await Products.findOneAndUpdate(
{ product: product.product },
{ $inc: { stocks: -product.quantity } }
);
await newProduct.save();
}
await newTransaction.save();
res.status(200).json(newTransaction);
} catch (error) {
res.status(400).json(error.message);
}
});

产品模型。最小值应为0。

const userInventoryModel = new Schema({
product: {
type: String,
trim: true,
unique: true,
},
stocks: {
type: Number,
default: 0,
min: 0,
},
basePrice: {
type: Number,
default: 0,
min: [0, "Value must be greater than 0."],
},
sellPrice: {
type: Number,
default: 0,
min: [0, "Value must be greater than 0"],
},
});

验证是一个中间件,Mongoose在将模型保存到数据库之前运行验证,而不是在findAndUpdate之前,所以请尝试

for (const product of order) {
let newProduct = await Products.findOne({ product: product.product });
//implement the business logic
newProduct.stocks = newProduct.stocks - product.quantity// it's an exmaple
await newProduct.save();
}

如果你想在更新后获取数据,使用new: ture

for (const product of order) {
let newProduct = await Products.findOneAndUpdate(
{ product: product.product },
{ $inc: { stocks: -product.quantity } },
{new : true}
);
await newProduct.save();
}
在这个方法中,你可以看到错误

最新更新