Sudheer KB
Sudheer KB

Reputation: 1606

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?

Upvotes: 4

Views: 176

Answers (1)

chridam
chridam

Reputation: 103365

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.

Upvotes: 1

Related Questions