提问者:小点点

如何更新(删除)嵌套数组中的文档


我有一个在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 });

考试的概念是,一个学生可以参加一个由几个考试组成的考试,每个考试都有一个类型名称(可以是数学或物理)和一个问题的列表,以及学生填写的相应答案。

此代码可以帮助在测试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);}})添加

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个答案

匿名用户

在下一个修饰符中使用$运算符:

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

首先必须在查询中使用$ElemMatch:运算符:

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

匿名用户

有一个mongo语法答案可能是其他人提供的。

我喜欢meteor的一个方面是,您可以随处使用JavaScript/Coffeescript。我谦虚地建议您将该策略扩展到mongo更新的使用中。我发现自己只是直接使用我的JSON/对象操作能力和$设置整个事情,而不是学习另一种语法。有些人会说,在证明它有效果之前限制检索的字段是不成熟的优化,因此,无论如何,您都可能检索数据。