【问题标题】:How can I update a certain key value in all nested objects with mongoose?如何使用猫鼬更新所有嵌套对象中的某个键值?
【发布时间】:2022-02-23 08:19:33
【问题描述】:

我有一个聊天应用程序,我正在尝试在其上添加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 });
        });
};

但不幸的是,它没有用

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

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    你应该使用positional operator - $[]

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

    Working example

    【讨论】:

    • 现在可以了,谢谢,谢谢
    猜你喜欢
    • 2014-07-13
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2023-01-17
    • 1970-01-01
    • 2020-03-01
    相关资源
    最近更新 更多