簡體   English   中英

數組中 object 的值不會在 Mongoose 中更新

[英]Value of object in array does not update in Mongoose

我有一個 Mongoose model 具有以下屬性:

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

我嘗試更改 object 中的投票字段,但在調用.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 是 model,但這也不起作用。 更改值后如何保存?

好的,我似乎找到了答案,必須使用更新 function:

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

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

試試這個代碼,它和你上面使用的邏輯相同,通過ID查找博客文章並檢查 object 中的字段命名tag是否為$exits votes ,如果確實如此,那么它將你的字段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();
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM