首页 > 解决方案 > 我们可以将多个 updateOne 转换为单个查询吗?

问题描述

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 },
    ),
  ),
);

标签: javascriptmongodbmongoose

解决方案


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()


推荐阅读