Skip to content
Advertisement

How do I add to existing data with findByIdAndUpdate instead of updating the data entirely

This is my object schema

var Message = mongoose.model('Message', {
    name: String,
    message: String,
    votes: Number

})

I am trying to update the number of votes like this

app.put('/messages/:id', (req, res) => {
    Message.findByIdAndUpdate({_id: req.params.id}, {votes: req.body.votes}).then(function(message){
        res.send(message)
    })
})

Let’s say the original amount of votes is 1, and the requested amount of votes is 5. The put request will update the amount of votes to be 5. Instead I would like to add the requested amount of votes on top of the existing amount of votes. Therefore it would theoretically be 1 + 5 which is 6 votes.

Is there anyway I can preserve the existing amount of votes which I can then add the requested amount on top of?

Advertisement

Answer

Consider using the $inc property to increment the value of votes rather than overwrite it.

Message.findByIdAndUpdate(req.params.id, { $inc: { votes: req.body.votes } })
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement