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

Node.js 如何更新(删除)嵌套数组中的文档,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我在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

我在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}}},选项,函数err,ref{ 伊弗{ 控制台。日志“将问题添加到考试”。红色,错误; callbackerr,null; }否则{ 控制台。记录“将问题添加到考试”。绿色+参考; callbacknull,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)

我尝试了这些方法,但没有一种是其他人可能提供的mongo语法答案

我喜欢meteor的一个方面是,您可以在任何地方使用javascript/coffeescript。我谦虚地建议您将该策略扩展到mongo更新的使用。我发现自己只是直接使用我的json/对象操作能力和$set,而不是学习另一种语法。有些人会说,在证明它会产生效果之前,限制您检索的字段是过早的优化,因此您可能仍然检索数据。

要在下一个修饰符中使用$operator:

{'$pull':{'test.$.questions':questionId} 您必须首先在查询中使用$elemMatch:operator:

{''u id':pid,检查:{$elemMatch:{type:type}}