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

247
Views
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 answers
Answer question

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 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!