【发布时间】:2021-07-24 22:31:16
【问题描述】:
我要做什么
我正在尝试使用 mongoose 更新 MongoDB 文档中字段数组内的所有对象。
我有什么
用户文档
{
id: <ObjectId>,
...
notifications: [
{
commissionId: <ObjectId>
commissioner: <ObjectId>
date: ...
description: "You have a new commission!"
},
{
commissionId: <ObjectId>
commissioner: <ObjectId>
date: ...
description: "You have a new commission!"
},
]
}
我想要的东西
{
id: <ObjectId>,
...
notifications: [
{
commissionId: <ObjectId>
commissioner: <ObjectId>
date: ...
description: "You have a new commission!"
read: true // Add read field with a value of true
},
{
commissionId: <ObjectId>
commissioner: <ObjectId>
date: ...
description: "You have a new commission!"
read: true // Add read field with a value of true
},
]
}
我正在使用 mongoose,现在我正在使用 findByIdandUpdate 方法。我试过了
使用一种方法来执行此操作,但它失败了。
await User.findByIdAndUpdate(
args.userId,
{
notifRead: true,
$set: {
"notifications.$.read": true, // FAIL "The positional operator did not find the match needed
// from the query."
},
},
{
new: true,
runValidators: true,
}
);
有没有办法简单地做到这一点?
【问题讨论】:
-
您可以使用 $[] 运算符来执行此操作。检查这个答案:stackoverflow.com/a/57622658/11711316