Mongoose:如何使用“$in”运算符更新对象数组?

问题描述 投票:0回答:1

我有以下架构:

const notificationSchema = new mongoose.Schema({


    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    notifications: [{
        title: {type: String},
        text: {
            type:String
        },
        seen: {type: Boolean},
        link: {type: String} 
    }]
})

我有一个 id 数组,我们称之为 arrayOfIds,其中每个 _id 与通知数组中的一个对象匹配。我想更新与 arrayOfIds 中的 id 匹配的所有对象(在通知数组中)。这是我目前正在做的事情:

const doc = await Notifications.updateMany(
            {_id: req.user.notifications, "notifications._id": {"$in": arrayOfIds}},
            {
                $set: {
                    "notifications.$.seen": true
                }
            },
            {
                multi: true
            }

        )

req.user.notifications 是整个文档的ObjectId。而通知是该文档中的一个字段,我想更新通知字段中与 arrayOfIds 匹配的所有条目。 由于某种原因,此查询仅更新通知数组中的一个对象,而不是匹配 arrayOfIds 中的所有 Id。 有人可以向我解释我做错了什么吗?我不明白为什么这不起作用。

arrays mongodb mongoose mongodb-query aggregation-framework
1个回答
0
投票

我已按以下方式完成此操作:-

const filter = { category: { $in: ['finance'] } };

const update = {
  $set: {
    temp: true
  }
};
const result = await db.updateMany(filter, update)
© www.soinside.com 2019 - 2024. All rights reserved.