更新嵌套数组中的$ inc,如何使索引动态化?

时间:2017-10-31 10:18:26

标签: mongodb mongoose

这是数据库

var UserSchema = new mongoose.Schema({
    profilePicture: {type: String, default: '../static/img/placeholder.jpg'},
    country: String,
    email: {
        type: String,
        unique: true,
        required: true,
        trim: true
    },
    name: {
        type: String,
        required: true,
        trim: true
    },
    password: {
        type: String,
        required: true
    },
    discussions: [{
            title: String,
            details: String,
            createdAt: {type: Date, default: Date.now},
            imgPath: {type: String, default: '../static/img/placeholder.png'},
            votesUp: {type: Number, default: 0},
            votesDown: {type: Number, default: 0},
            viewCount: {type: Number, default: 0},
            discussionsId: String,
            discussionReplay: [{
                    comment: String,
                    commentImg: String,
                    commentDate: {type: Date, default: Date.now},
                    commentOwner_id: String,
                    commentOwnerImg: String,
                    commentOwnerName: String,
                    commentVotesUp: {type: Number, default: 0},
                    commentVotesDown: {type: Number, default: 0}
            }]
    }]
});

我想增加commentVotesUp,但我在discussionReplay数组中有很多评论。此代码有效,但这是静态的。我只能访问0索引的评论对象。我怎样才能使零动态。 讨论。$。discussionReplay。的 0 .commentVotesUp 无论如何传递变量?

        User.update({_id: req.body.user_id, discussions: {
          $elemMatch: { discussionsId: req.body.discussion_id} }},
                    {$inc: { "discussions.$.discussionReplay.0.commentVotesUp" : 1}},
                        function(err,item){
                            res.send('working')
        });

0 个答案:

没有答案