【问题标题】:Can't seem to increment a nested value in mongoose似乎无法在猫鼬中增加嵌套值
【发布时间】:2017-05-13 11:21:00
【问题描述】:

我似乎无法在 mongoose 中增加嵌套值。我已经尝试了在网上找到的多个修订版,但似乎都没有奏效。我正在使用 mongodb 3.2 版和 mongoose 4.9.5。

这个项目是一个论坛。有一个带有“posts”属性的线程,它是一个数组。每个帖子都有一个“like”属性,每个喜欢该帖子的人都有一个“users”属性,以及一个应该随着每次更新而增加的 count 属性。这是我的模型:

const threadSchema = mongoose.Schema({  
title: {type: String, required: true},
date: {type: Date, default: Date.now},
author: {type: String, required: true},
content: {type: String},
posts: [{
    content: {type: String, required: true},
    user: {type: String, required: true},
    created: {type: Date, default: Date.now},
    likes: {
        users: [String],
        count: {type: Number, default: 0}
    },      
    comments: [{
        comment: {type: String},
        user: {type: String},
        created: {type: Date, default: Date.now},
        likes: {type: Number, default: 0}
    }]
}]
});

这是我的更新代码。它可以很好地推送到 posts.likes.users 数组,但不会增加:

Threads.findOneAndUpdate({"posts._id": req.body.postId}, {"$push": {"posts.$.likes.users": user}}, {$inc: {"posts.$.likes.count": 1}})

我也试过这些版本:

 {"$inc": {"posts.likes.count": 1}}
 {"$inc": {"posts.$.likes.count": 1}}
 {"$inc": {"posts.$.likes.$.count": 1}}

谢谢。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    好像我不能在同一行进行两次编辑。将它们分开似乎可以解决问题。

    Threads.findOneAndUpdate({"posts._id": req.body.postId}, 
    {"$push": {"posts.$.likes.users": user}})
    .exec()
    .then((post) => {
        //some stuff
    })
    
    Threads.findOneAndUpdate({"posts._id": req.body.postId}, 
    ({"posts._id": req.body.postId}, 
    {$inc: {"posts.$.likes.count": 1}})
    .exec()
    .then((post) => {
        // some other stuff
    })
    

    【讨论】:

      猜你喜欢
      • 2021-06-07
      • 2021-08-08
      • 2012-02-17
      • 1970-01-01
      • 2016-06-08
      • 2021-03-23
      • 2020-06-04
      • 2019-03-22
      • 2018-06-23
      相关资源
      最近更新 更多