2013-08-30 61 views
0

我有一个用mongoose实现的mongodb测试模式。如何更新(删除)嵌套数组中的文档

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

测试的想法,是一个学生可能会参加一些考试的测试,每次考试都有一个类型名称(可以是数学或物理)和问题的列表OBJECTID以及相应的回答充满由学生。

此代码可以帮助在测试中添加新的问题和答案 TestModel.update({'_ id':pid,'exam.type':type},{'$ push':{'exam (问题):questionsId,'answer':answer}}},options,function(err,ref){if(err){ ,ERR); 回调(ERR,NULL);} 其他{ 的console.log(“添加问题Exam'.green + REF);
回调(NULL,REF);} } ) 它的工作原理以及通过添加,但删除问题和答案,更新不起作用。

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) 

我尝试了这些方法,但这些工作

回答

-2

的有一个蒙戈语法回答别人可以提供。

我喜欢的流星的一个方面是你可以随处使用javascript/coffeescript。我虚心地建议你把这个策略扩展到你使用mongo更新。我发现自己直接使用我的json/object操作能力,$设置了整个事情,而不是学习另一种语法。有人会说,限制你检索的字段是不成熟的优化,直到证明它会有效果,所以你可能无论如何检索数据。

0

在未来修改使用$操作:

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

您必须在第一次使用$elemMatch:运营商在查询:

{'_id': pid, exam: { $elemMatch: {type: type} } }