How to update(remove) a document in the nested array

16 views
Skip to first unread message

xi sizhe

unread,
Aug 30, 2013, 4:45:17 PM8/30/13
to mongoo...@googlegroups.com

I have a test schema of mongodb implemented in mongoose.

var TestSchema = new mongoose.Schema({ exam:[ Exam ] });

var ExamSchema  = mongoose.Schema({type:String, questions: [  { question:{ type: ObjectId, ref: 'Question' }, answer:String } ]    });

var QuestionSchema = mongoose.Schema({ desciption:String, solution:String });

The idea of the test, is a student might participate a test of several exams, each exam has a type name (could be Math or Physics ) and a list of question ObjectID as well as the corresponding answer filled by the student.

This code could help to add new question and answer to certain exam in the test TestModel.update({'_id':pid,'exam.type':type},{'$push':{'exam.$.questions':{'question':questionsId,'answer':answer}}},options,function(err,ref){ if(err) { console.log('add question to Exam'.red,err); callback(err, null); }else{ console.log('add question to Exam'.green+ref);
callback(null,ref); } }) It works well by adding but it comes to removing a question and answer, the update doesn't work.

Model.update({'_id':pid,'exam.type':type},{'$pull':{'exam.$.questions':questionId}},options,function(err,ref)

Model.update({'_id':pid,'exam.type':type},{'$pull':{'exam.$.questions.question':questionId}},options,function(err,ref)

Model.update({'_id':pid,'exam.type':type,'exam.questions.question':questionId},{'$pull':{'exam.$.questions.$.question':questionId}},options,function(err,ref)

Model.update({'_id':pid,'exam.type':type,'exam.questions.question':questionId},{'$pull':{'exam.questions.$.question':questionId}},options,function(err,ref)

I tried these methods, but none of these work

Reply all
Reply to author
Forward
0 new messages