首页 > 解决方案 > 数组中对象的值在 Mongoose 中不更新

问题描述

我有一个具有以下属性的猫鼬模型:

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

我尝试更改对象内的投票字段,但在调用 .save() 后,该值未更新。我试过使用:

post.markModified('votes')

调用它的代码:

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    
    })

其中 post 是模型,但这也不起作用。更改值后如何保存?

标签: node.jsmongodbmongoosemongoose-schema

解决方案


好的,我似乎找到了答案,必须使用更新功能:

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

推荐阅读