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

测试的想法是,一个学生可能参加几门考试的考试,每门考试都有一个类型名称(可以是 Math 或 Physics )和一个问题列表 ObjectID 以及学生填写的相应答案。

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

我尝试了这些方法,但这些方法都不起作用

4

2 回答 2

0

$在 next 修饰符中 使用运算符:

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

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

{'_id': pid, exam: { $elemMatch: {type: type} } }
于 2016-06-23T07:26:58.083 回答
-2

其他人可能会提供一个 mongo 语法答案。

我喜欢流星的一个方面是你可以在任何地方使用 javascript/coffeescript。我谦虚地建议您将该策略扩展到您对 mongo 更新的使用。我发现自己只是直接使用我的 json/object 操作能力并 $set 整个事情,而不是学习另一种语法。有人会说,在证明它会产生影响之前限制您检索的字段是过早的优化,因此您可能无论如何都要检索数据。

于 2013-08-30T20:18:45.617 回答