[英]Update all objects in a MongoDB document array field
我正在尝试做的事情
我正在尝试使用 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,
}
);
有没有办法简单地做到这一点?
可以使用all positional operator $[]
,您可以这样做:
await User.update(
args.userId,
{
$set: {
"notifications.$[].read": true,
},
},
{
muti: true
}
);
有关更多详细信息,您可以在此处查看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.