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

248
Visualizações
Update value inside a array inside a mongoose record

User Schema:

var userSchema = new mongoose.Schema({
    user: String,
    data: [{}]
});

In the schema above, I am adding question and option(MCQ) user marked inside the data array. I can add new answers successfully but can't update already answered question with different options.

Server side code:

let user = await User.findOne({ user: req.body.user });
let checkUser = user.data.filter(res => res.quesId == req.body.id);
if (checkUser.length) {
    // Logic for updating
} else {
    await user.data.push({
        quesId: req.body.id,
        option: req.body.opt
    });
    user.save();
}

So what I want to do is that if the user answered the same question(determined by req.body.id) with different option(req.body.opt), it should be updated in the already existing record.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

To update an object inside an array, you need to remove the original object then create a new one with the new data included.

Example:

// Define required variables
let user = await User.findOne({ user: req.body.user });
let data = user.data;
let checkUser = data.filter(res => res.quesId == req.body.id);

// If the question already exists
if (checkUser.length > 0) {
    // Loop through the questions that already exist
    checkUser.forEach(question => {
        // Remove the question from the users data
        data.splice(data.indexOf(question), 1);
        // Append the new data onto the array
        data.push({
            quesId: req.body.id,
            option: req.body.opt
        });
        // Save the new data
        user.data = data;
        user.save();
    });
} else {
    // If the question doesn't already exist, create it
    (user.data).push({
        quesId: req.body.id,
        option: req.body.opt
    });
    // Save the changed data
    user.save();
}
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