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

296
Views
Unable to update nested Model in mongoose

I am creating poll app. My schema definitions are as below

var option = new mongoose.Schema({
    title: {type: String, required: true},
    votes: { type: Number, default: 0 }
});

var poll = new mongoose.Schema({
  question: { type: String, required: true, unique: true},
  options: { type: [option], required: true}
});

I have tried

app.put('/vote/:id', function(req, resp) { 
    Poll.findById(req.params.id , function(err, pol) { 
        pol.options.findById(req.body.id, function(err, option){// getting error in this line
            //do my stuff
        });
    });
});

But I am getting an error. How do I increase votes by one using mongoose?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Use the $inc update operator together with the $ positional operator as

app.put('/vote/:id', function(req, resp) { 
    Poll.findOneAndUpdate(
        { "_id": req.params.id, "options._id": req.body.id },
        { "$inc": { "options.$.votes": 1 } },
        { "new": true }
        function(err, pol) { 
            // pol contains the modified document
        }
    );
});

The $ positional operator facilitates updates to arrays that contain embedded documents like the options array in your case. It allows you to access the fields in the embedded documents with the dot notation on the $ operator.

over 4 years ago · Santiago Trujillo 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!