如何使用 mongoose 更新所有嵌套对象中的某个键值?

How can I update a certain key value in all nested objects with mongoose?

我有一个聊天应用程序,我想在上面添加 seen 功能。 我正在尝试执行一个可以更新所有聊天消息(已见)列的查询。

架构如下:

const messageSchema = new mongoose.Schema({
    senderId: {
        type: String,
        required: true
    },
    message: {
        type: String,
        required: true
    },
    seen: { // I'm trying to update this in all the documents !!
        type: Boolean,
        default: false 
    }
}, {timestamps: true});

const chatSchema = new mongoose.Schema({
    messages: [messageSchema]
});

正如您在这里看到的,我在消息架构中有一个 seen 属性(嵌套在聊天架构中)

所以我只想进行一次聊天,更新其中的所有消息并将 seen 列更新为 true

我试过了:

const messagesSeen = async (req, res) => {
    const chatId = req.params.id;

    await Chat.findByIdAndUpdate(
        chatId,
        {
            $set: { 'messages.seen': true },
        },
        { new: true }
    )
        .then((chat) => {
            return res
                .status(200)
                .json({ chat });
        })
        .catch((error) => {
            return res.status(500).json({ message: error.message });
        });
};

但不幸的是,它没有用

所以,希望找到解决办法。 谢谢

你应该使用 positional operator - $[].

await Chat.findByIdAndUpdate(
  chatId,
  {
    $set: { "messages.$[].seen": true },
  },
  { 
    new: true 
})

Working example