mongodb collection:
"_id": ObjectId("5e2ac528e9d99f3074f31de7"),
"publications": [
{
"_id": ObjectId("5e2ac528e9d99f3074f31de8"),
"name": "Times of India",
"productCode": "TCE1",
"tradeCopies": 40
},
{
"_id": ObjectId("5e2ac528e9d99f3074f31de9"),
"publicationName": "Economic Times",
"productCode": "ECE1",
"tradeCopies": 100
}
],
"orderCreatedBy": ObjectId("5e2977e1cc1208c65c00648b"),
"submittedTo": ObjectId("5e2555363405363bc4bf86c2"),
Nodejs 代码
我会得到多个"产品代码">,如"TCE1"、"ECE1"等,我需要根据他们的产品代码一次性更新所有对象数组元素的贸易副本
这是我尝试过的
exports.editOrder = async (req, res, next) => {
const { orderId, dealerId, productCode, tradeCopies } = req.body;
try{
const orders: await Order.updateOne(
{ _id: orderId,
submittedTo: dealerId,
"publications.productCode": productCode},
{$set:{"publications.$.tradeCopies":50}}
)
res.status(200).json({
orders,
message: "order submitted"
});
} catch (error) {
res.send(error);
}
};
关注
1-此查询仅根据匹配的产品代码更新 1 个数组对象元素我希望所有交易所有数组对象的副本根据其产品代码在 onego 中更新
2-上述查询仅在mongo Shell中工作,而不是在nodejs驱动程序中起作用,每当我在nodejs查询vscode中删除双引号时,都显示可能会有错误
你想使用 arrayFilters。
const orders: await Order.updateOne(
{ _id: orderId,
submittedTo: dealerId,
"publications.productCode": productCode
},
{ $set: { "publications.$[element].tradeCopies":50 } },
{ arrayFilters: [ { "element.productCode": productCode } ] }
)
我不确定您删除双引号是什么意思,但此代码段与 nodejs 驱动程序兼容。