[英]Can we transform multiple updateOne into a single query?
我有一个看起来像这样的数组orderProducts
orderProducts = [
{_id: _id, color: 'blue', quantity: '2'},
{_id: _id, color: 'red', quantity: '4'},
...
];
我有这个查询循环,可以执行我需要做的事情,找到文档并减去数量。
我想知道是否可以将这种操作分组为一个查询
编辑:我只想发送一个查询到数据库,所以如果其中一个查询失败,一切都会失败
// Working example of the operation i need to do
await Promise.all(
orderProducts.map(
product => Product.findOneAndUpdate(
{ _id: product._id, 'colors.color': product.color },
{ $inc: { 'colors.$.quantity': -product.quantity } },
{ new: true },
),
),
);
const orderProducts = [ {_id: 1, color: 'blue', quantity: '2'}, {_id: 2, color: 'red', quantity: '4'}, {_id: 3, color: 'red', quantity: '3'}, {_id: 4, color: 'green', quantity: '4'}, {_id: 5, color: 'red', quantity: '3'}, ]; const run = async () => { const output = await Promise.all(orderProducts.map(async (product) => { const result = await Product.findOneAndUpdate( { _id: product._id, 'colors.color': product.color }, { $inc: { 'colors.$.quantity': -product.quantity } }, { new: true } ) return result })) console.log(output) } run()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.