Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You should use positional operator$[].

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

Working example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading