javascript - 更新 Mongoose 模型内的数组

标签 javascript node.js mongodb mongoose

我必须对以下 Mongoose 模型进行更新。

var room_schema = new Schema({
title:          { type: String, required: true },
questions:    [{    //array of reflections
    q_index: {type: Number},
    q_text: { type: String},
    responses: [{   //array of 
        student: { type: Schema.Types.ObjectId, ref: 'User' },
        response: { type: String }
    }]
  }]
});

module.exports = mongoose.model('Room', room_schema);

所需值位于对象中,如下所示

x = {
room: ObjectId("586a0aa0232a3918c8b7f5c9"),
student: ObjectId("5863918c85c9ba0aa0232a7f"),
question: 0,
msg: "Some Message"    
}

现在,我想更新房间。我尝试做这样的事情

Room.update(
  {_id:x.room, 
    'questions.q_index':x.question,
    'questions.responses.student':x.student},
  {$set:{
    'responses.$.student.response' : x.msg
  }},function(err, data){
    if(err){throw err}
    console.log(data);
  }
);

返回的消息是{ ok: 0, n: 0, nModified: 0 },不用说更新没有发生。 此外,Room 中可能没有响应数组。我希望,如果是这种情况,那么应该创建数组然后更新。 请给我一些指导。

最佳答案

抱歉,但我无法写评论,因为我没有足够的代表,所以我被迫写我的通知作为答案。

当您通过 _id 搜索房间时,我在您的第一个查询中注意到了一些内容。尝试将 _id 放在引号中,例如“_id”,因为与此帖子相关的内容应该是这样的

stackoverflow: updating-an-array-inside-a-mongoose-model

关于javascript - 更新 Mongoose 模型内的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41544433/

相关文章:

mysql - 管道 `request` 响应 MySQL 回调中的服务器响应未按预期工作? Node

java - 最新代码中的 FHIR _id 至 id 更改

javascript - 如何映射 `.find()`返回的数据?

javascript - HTML 框格式

javascript - Bootstrap 日期时间选择器不工作

javascript - 在 Windows 上,发送并返回 CORS 预检 OPTIONS 请求,但随后 PUT 请求将无限期挂起 'pending'

mongodb 分片键使用

javascript - 通过 AJAX 将对象传递给 PHP

javascript - 如何在 css/html/javascript 中为我的文本添加边框

javascript - 使用 csv-parser 只返回文件头