0

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

2 Answers 2

0

To use $ operator in the next modifier:

{'$pull': {'exam.$.questions': questionId}

You must at first use $elemMatch: operator in your query:

{'_id': pid, exam: { $elemMatch: {type: type} } }
Sign up to request clarification or add additional context in comments.

Comments

-2

There is a mongo syntax answer someone else may provide.

One aspect of meteor I love is that you get to use javascript/coffeescript everywhere. I humbly suggest you extend that strategy to your use of mongo updates. I find myself just using my json/object manipulation abilities directly and $set the whole thing, rather than learning another syntax. Some would say it is premature optimization to limit the fields you retrieve until proven it would have an effect, so you probably retrieve the data anyway.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.