Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda