我需要更新集合内数组内对象中的字段“rightAnswer”。
如何将特定评论的 bool 值更改为正确问题的 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){});
关于node.js - 更新集合内数组内的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28439292/