簡體   English   中英

在貓鼬模型內部更新數組

[英]Updating an array inside a Mongoose Model

我必須對以下貓鼬模型進行更新。

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:在一個貓鼬模型內部更新一個數組

暫無
暫無

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

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