Home > front end >  How can I update a certain key value in all nested objects with mongoose?
How can I update a certain key value in all nested objects with mongoose?

Time:02-23

I have a chat application that I'm trying to add seen functionality on it. I'm trying to execute a query that could update all chat messages (seen) columns.

here's the schema:

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]
});

As you can see here, I have a seen property in the message schema (which is nested inside the chat schema)

so I just want to get a single chat, update all messages inside it and update seen column to be true

I tried that:

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 });
        });
};

but unfortunately, it didn't work

so, hope to find a solution. thank you

CodePudding user response:

You should use positional operator - $[].

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

Working example

  • Related