Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

249
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda