在嵌套数组内查找并删除文档

我努力删除mongoDB中嵌套的arrray内的元素。

可以说我有这个模式:

var question = new Schema({ problem: { type: String, required: true }, multipleChoices: [{ type: String, required: true }], correctAnswer: { type: Number, required: true } }); var testCategorySchema = new Schema({ category: { type: String, required: true }, tests: [{ version: { type: String, required: true }, questions: [question] }] }); 

例如,我有这样的模式的实例:

 { category: "Math", tests: [ { _id : ObjectId("580859310a0d4b40ac1c6034"), version: "1A", questions: [ { problem: "blablabla", multiplechoices: [ "bla bla", "blb blb", "blc blc" ], correctAnswer: 1 }, { problem: "blibliblibli", multiplechoices: [ "bla bla", "blb blb", "blc blc" ] correctAnswer: 1 } ] }, { _id : ObjectId("580859310a0d4r40ax1c5034"), version: "1B", questions: [ { problem: "auauauauau", multiplechoices: [ "bla bla", "blb blb", "blc blc" ] correctAnswer: 1 }, { problem: "blibliblibli", multiplechoices: [ "bla bla", "blb blb", "blc blc" ] correctAnswer: 1 } ] } ] } 

例如,我怎样才能删除问题:“blablabla”在类别math和版本1A使用mongooseJS?

我已经使用此代码删除math类别和版本1A中的问题:

 TestCategory .findOne( { category: req.params.testCategory, 'tests.version': req.params.testVersion }, { 'tests.version.$': 1 } ) .then(function(testVersion) { res.send(testVersion); }) .catch(function(err) { console.log(err); next(err); }); 

例如,我searchmath类别和版本1A,该代码的结果是这样的:

 _id: "580859190a0d4b40ac1c6033", tests: [ { _id : ObjectId("580859310a0d4b40ac1c6034"), version: "1A", questions: [ { problem: "blablabla", multiplechoices: [ "bla bla", "blb blb", "blc blc" ], correctAnswer: 1 }, { problem: "blibliblibli", multiplechoices: [ "bla bla", "blb blb", "blc blc" ] correctAnswer: 1 } ] } ] 

结果已经过滤,所以只显示版本1A(尽pipecategoryId仍然显示)。 现在我很困惑如何正确和好的方法来删除这个问题。

您需要使用update与位置操作符$为了更新正确的testing,然后使用$pull删除问题:

 TestCategory.update( { category: 'Math', 'tests.version': '1A' }, { $pull: { 'tests.$.questions': { problem: 'blablabla' } } } )