Search code examples
node.jsmongodbmongoosemongoose-schema

Value of object in array does not update in Mongoose


I have a Mongoose model with the following property:

new Schema({
 votes: [{tag: String, votes: Number}]
})

I try to change the votes field inside the object but after I call .save(), the value is not updated. I have tried using:

post.markModified('votes')

The code where it is called:

let post = await Post.findById(req.body.postId) //Express request

for(let item in post.votes){ //votes is the array as in the model
        if(item.tag === tag){
            item.votes += 1
            break
        }
    }

post.save({}, (err, doc) => {
        //Other stuff    
    })

where post is the model, but this also does not work. How can I save it after changing the value?


Solution

  • Okay I seem to have found an answer to this, has to use the update function:

    Post.updateOne({ _id: post.id, 'votes.tag': tag }, { $set: { 'votes.$.votes': 1 } }, (err, raw) => {})