2015-05-03 133 views
0

我有幾個貓鼬模型在我的應用程序 - 賦值,submisssion和文件。刪除嵌套的對象引用mongoose

var assignmentSchema = new Schema({ 
    submissions:[{ 
     type: mongoose.Schema.Types.ObjectId, 
     ref: 'Submission' 
    }] 
}); 

var submissionSchema = new Schema({ 
    assignment: { 
     type: mongoose.Schema.Types.ObjectId, 
     ref: 'Assignment' 
    }, 
    files: [{ 
     type: mongoose.Schema.Types.ObjectId, 
     ref: 'File' 
    }], 
}) 

var fileSchema = new Schema({ 
    submission: { 
     type: mongoose.Schema.Types.ObjectId, 
     ref: 'Submission' 
    } 
}) 

我定義了一個刪除掛鉤的分配,因此,當一個分配是從我的MongoDB刪除,提交的所有文件都被刪除了。

assignmentSchema.pre('remove', function (next) { 
    var assignment = this; 

    assignment.model('Class').update(
     {_id: {$in: assignment.classes}}, 
     {$pull: {assignments: assignment._id}}, 
     {multi: true}, 
     next 
    ); 

    //will delete all submissions that were in the assignment 
    assignment.model('Submission').remove(
     {_id: {$in: assignment.submissions}}).exec(); 
     next 
}); 

它工作正常,但我也想刪除所有與刪除提交相關的文件。我怎樣才能做到這一點?

回答

2

您必須爲您的提交文檔設置預刪除掛鉤。
然後在assignSchema循環中通過assignment.submissions數組,查找每個分配文檔並對該文檔執行刪除操作。 這裏是一個例子。未經測試。

assignmentSchema.pre('remove', function(nextAction) { 
    var assignment = this; 

    assignment.model('Class').update({ 
      _id: { 
       $in: assignment.classes 
      } 
     }, { 
      $pull: { 
       assignments: assignment._id 
      } 
     }, { 
      multi: true 
     }, 
     next 
    ); 

    Async.each(assignment.submissions, function(subId, next) { 
     submissionSchema.findById(subId).exec(function(err, submission) { 
      submission.remove(); 
      next(); 
     }) 
    }, function() { 
     nextAction(); 
    }) 
}); 



submissionSchema.pre('remove', function (next) { 
///remove files here. 
}) 
+0

工程!謝謝.. –