更新集合内数组内的对象

update object inside array that is inside collection

我需要更新集合中数组中对象中的字段 "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){});
Question.update({_id: req.body.question._id, 
                "answers": {$elemMatch: {_id: req.body.answer._id}}},
                {$set: {"answers.$.rightAnswer": true}}, 
                function(req, res){});