簡體   English   中英

更新集合內部數組中的對象

[英]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){});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM