猫鼬中数组中对象的值不会更新

时间:2020-07-22 11:37:13

标签: node.js mongodb mongoose mongoose-schema

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

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是模型,但这也不起作用。更改值后如何保存?

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

.save()不会更新数组。

您将不得不使用查询更新阵列。

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

// update the votes aray with the modified votes array:
Post.findByIdAndUpdate(req.body.postId, {votes: votes}, (err, doc => {
// do your stuff
}))

答案 2 :(得分:0)

尝试这段代码,它的逻辑与您上面使用的逻辑相同,按ID查找博客帖子,并检查对象tag votes中名为$exits的字段是否这样做,然后将您的字段likes的值增加+1。

express.method("/:postId", async (req, res) => {
    try {
        const updatedBlog = await Post.findOneAndUpdate(
            {
              _id: req.body.postId,
              "votes.tag": { $exists: true }
            },
            {
                $inc: { "item.votes": 1 }
            },
            { new: true } //to return the new document
        );
        res.json(updatedBlog);
    } catch (error) {
        res.status(400).end();
    }
});