javascript - 我们可以将多个 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 },
),
),
);
解决方案
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()
推荐阅读
- php - 为什么我的外部样式 css 表在 IE 中没有通过,但在 Chrome 中可以通过?
- chart.js - cartjs 工具提示显示在图表上的错误位置
- python - 梯度计算
- python - 从 TextFileReader 对象转换为 pandas DataFrame
- swift - TCP/IP 与 NWConnection 在 swift 中的未知结果
- git - git describe 不适合 git 流程?
- php - Laravel 5.8 Eloquent Create() 返回错误的 ID
- r - 在 r 中拆分一列
- javascript - 从外部确定哪些测试用例失败 - Javascript
- c# - ManagedBass Wasapi dll UWP