Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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)

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should use positional operator - $[].

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

Working example

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!