0
var Poll = mongoose.model('Poll', {
title: String,
votes: {
    type: Array,
    'default' : []
}
});

I have the above schema for my simple poll, and I am uncertain of the best method to change the value of the elements in my votes array.

app.put('/api/polls/:poll_id', function(req, res){
Poll.findById(req.params.poll_id, function(err, poll){

// I see the official website of mongodb use something like
// db.collection.update()
// but that doesn't apply here right? I have direct access to the "poll" object here.

Can I do something like
poll.votes[1] = poll.votes[1] + 1; 
poll.save() ?

Helps much appreciated.

});
});

1 Answer 1

1

You can to the code as you have above, but of course this involves "retrieving" the document from the server, then making the modification and saving it back.

If you have a lot of concurrent operations doing this, then your results are not going to be consistent, as there is a high potential for "overwriting" the work of another operation that is trying to modify the same content. So your increments can go out of "sync" here.

A better approach is to use the standard .update() type of operations. These will make a single request to the server and modify the document. Even returning the modified document as would be the case with .findByIdAndUpdate():

Poll.findByIdAndUpdate(req.params.poll_id,
    { "$inc": { "votes.1": 1 } },
    function(err,doc) {

    }
);

So the $inc update operator does the work of modifying the array at the specified position using "dot notation". The operation is atomic, so no other operation can modify at the same time and if there was something issued just before then the result would be correctly incremented by that operation and then also by this one, returning the correct data in the result document.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.