我必须对以下 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”,因为与此帖子相关的内容应该是这样的
关于javascript - 更新 Mongoose 模型内的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41544433/