node.js - 更新集合内数组内的对象

标签 node.js mongodb

我需要更新集合内数组内对象中的字段“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/

相关文章:

java - MongoDB 聚合到 Java

MongoDB - 太多连接 w/node.js

c# - 表达式树 mongodb linq 不支持 AsQueryable 方法

node.js - 使用 node.js admin sdk 创建 token 时的 Firebase REST 身份验证

Node.js sendgrid 实现

javascript - 使用 findOneAndUpdate $pull 和填充不更新或填充

mongodb - Meteor MongoDB 中的自定义排序

javascript - 比较数组中的两个元素,如果某些属性匹配,则更新第一个数组的属性

node.js - 将所有属性标记为是否需要 Joi

javascript - 在 Node.js 中,如果我正在编写一个长时间运行的函数,我应该使用 setTimeout