更新集合内部的数组内的对象

时间:2015-02-10 18:41:17

标签: node.js mongodb

我需要更新集合内部对象内的对象“rightAnswer”。

如何针对正确的问题将特定注释的布尔值更改为true。

在Angular中,我将问题的id和评论的id传递给后端。但在后端我不知道如何更新该字段。我使用MEAN堆栈。

问题架构:

var questionSchema = new mongoose.Schema({
    title: {type : String, default : '', trim : true},
    text: {type : String, default : '', trim : true},
    publisher_id: {type : mongoose.Schema.ObjectId, ref : 'User'},
    answers: [{
        body: { type : String, default : '' },
        user: { type : mongoose.Schema.ObjectId, ref : 'User' },
        rightAnswer: { type : Boolean, default: false },
        createdAt: { type : Date, default : Date.now }
    }],
    date  : {type : Date, default : Date.now}
});

我的快递路线:

  Question.update({_id: req.body.question._id}, {"answers._id": req.body.answer._id}, {$set: {"answers.$.rightAnswer": true} }, function(req, data){
    res.json(data);
  });

解决方案:

Question.update({_id: req.body.question._id, 
                "answers": {$elemMatch: {_id: req.body.answer._id}}},
                {$set: {"answers.$.rightAnswer": true}}, 
                function(req, res){});

1 个答案:

答案 0 :(得分:0)

Question.update({_id: req.body.question._id, 
                "answers": {$elemMatch: {_id: req.body.answer._id}}},
                {$set: {"answers.$.rightAnswer": true}}, 
                function(req, res){});
相关问题