问题描述
我想做什么
我正在尝试使用 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
}
);
有关详细信息,您可以查看here。