0

I have to do an update on the following 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);

Required values are in an object as

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

Now, i want to update the room. I tried doing something like this

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);
  }
);

The msg which is being returned is { ok: 0, n: 0, nModified: 0 } and needless to say the update is not happening. Also, there is a possibility that the Room may not have a response array in it. And i expect that, if that is the case, then the array should be created and then updated. Please give me some guidance.

Piyush Pandey
  • 306
  • 3
  • 17

1 Answers1

1

Sry, but I can't write a comment since I don't have enough of rep, so I'm forced to write my notice as an answer.

I notice something in your first query when you search for a room by it's _id. Try to put _id in quotes like this "_id", because it should be like this relating to this post

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

Community
  • 1
  • 1
JSEvgeny
  • 2,550
  • 1
  • 24
  • 38
  • This is giving the exact same o/p: `{ ok: 0, n: 0, nModified: 0 }` May be something else is there which i am missing. May be i will have to write the whole deal. – Piyush Pandey Jan 09 '17 at 12:15
  • Check the link I sent, mb there will be something interesting. You should also check this http://mongoosejs.com/docs/subdocs.html – JSEvgeny Jan 09 '17 at 12:19