无法在mongoose中更新嵌入式数组中的属性

时间:2013-12-05 20:13:00

标签: node.js mongodb mongoose

我正在使用mongoose / n开发评论系统, 用户可以评论,并且喜欢在reddit中,用户应该向上或向下投票。 我有以下评论方案:

var commentSchema = new Schema({
  text: String,

  level: { type: Number, min: 0, max: 30, default: 0},
  slug: String,
  full_slug: String,

  discussion_id: { type: Schema.ObjectId, ref: 'Uranus' },
  parent_id: {type: Schema.ObjectId,ref: 'Comment'},

  score: [{
        upvote: {type: Number,min: 0,max: 9000},
        downvote: {type: Number,min: 0,max: 9000},
        voter: {type: Schema.ObjectId,ref: 'Account'}
    }],

  updated: { type: Date, default: Date.now },
  created: { type: Date, default: Date.now },
  author: { type: Schema.ObjectId, ref: 'Account' },
});

它工作得很好,但我不知道如何更新得分数组。它只是不起作用。 这是我得到的样本json-data:

{
"__v" : 0,
"_id" : ObjectId("52a0d4ff779edff16d000006"),
"author" : ObjectId("529dfdda6b2d7a450c000009"),
"created" : ISODate("2013-12-05T19:33:19.229Z"),
"discussion_id" : ObjectId("529f7b04cbab31cc3e000004"),
"full_slug" : "2013.12.05.19.33.19:e1CDx79g8",
"level" : 0,
"score" : [ 
    {
        "upvote" : 1,
        "downvote" : 0,
        "voter" : ObjectId("529dfdda6b2d7a450c000009"),
        "_id" : ObjectId("52a0d4ff779edff16d000007")
    }, 
    {
        "upvote" : 0,
        "downvote" : 1,
        "voter" : ObjectId("52a0d9883027a89d6e000002"),
        "_id" : ObjectId("52a0d9903027a89d6e000004")
    }, 
    {
        "upvote" : 0,
        "downvote" : 1,
        "voter" : ObjectId("52a0d99a3027a89d6e000005"),
        "_id" : ObjectId("52a0d9a63027a89d6e000007")
    }
],
"slug" : "e1CDx79g8",
"text" : "A Comment",
"updated" : ISODate("2013-12-05T19:33:19.229Z")
}

所以,我只是通过

更新评论
var query = {
  'score.voter': mongoose.Types.ObjectId(String('52a0d9883027a89d6e000002'))
};
Comment.update( query, {$set: {"score.$.upvote": 10}} )

问题是,它只是没有更新。

我知道,关于这个问题还有一些其他问题,但所有解决方案对我都不起作用。我希望有人可以帮助我。

更新

发现问题,好像你必须对更新函数进行回调,如下所示:

Comment.update( query, {$set: {"score.$.upvote": 10}}, { multi: false }, function(err,n){
    console.log("affected rows:", n)
});

0 个答案:

没有答案