2016-09-09 35 views
1

我正試圖讓'貓'中間件工作在貓鼬上。貓鼬級聯中間件,多級

我有一個數據庫中,我有:

'modules' -> 'modulesInst' -> 'assignments' -> 'studentAssignments' 

所以,當模塊刪除,它瀑布「modulesInst」,而當modulesInst刪除它刪除「作業」相關的,然後用相同的「學生作業」 。

問題是我只能得到它在一個級別上工作。

頂級架構和 '刪除' 中間件(模塊)

var modulesSchema = new Schema (
     { 
      _id: Number, 
      moduleName: String, 
      moduleLeader: String 
     } 
    ); 

modulesSchema.pre('remove', function(next){ 
    modulesInst.remove({modID: this._id}).exec(); 
    next(); 
}); 

第二級模式和 '刪除' middleare(moduleInst)[其中中間件停止級聯]

var modulesInstSchema = new Schema (
    { 
     year: Number, 
     semester: String, 
     modID: [{ type: Schema.Types.Number, ref: 'Module' }], 
    } 
); 

modulesInstSchema.pre('remove', function (next) { 
    assignment.remove({modInsID: this._id}).exec(); 
    next(); 
}); 

第三級架構和'刪除'中間件(賦值)[中間件不會觸發]

var assignmentSchema = new Schema (
    { 
     code: String, 
     assignName: String, 
     modInsID: [{ type: Schema.Types.Number, ref: 'ModuleInst' }], 
    } 
); 

assignmentSchema.pre('remove', function (next) { 
    studentAssign.remove({assID: this._id}).exec(); 
    next(); 
}); 

有沒有一個簡單的把戲我失蹤,以保持級聯?由於文檔不清楚,找不到示例。

回答

0

Model.remove()方法不會觸發中間件。從docs

注:對於刪除(沒有查詢鉤),只爲文件。如果你設置了一個'remove'鉤子,當你調用myDoc.remove()時它會被觸發,而不是當你調用MyModel.remove()時。

這就是說,你必須在文檔級別做到這一點,例如(使用bluebird的承諾):

modulesInt 
    .find({ modID: this._id }) 
    .then((modules) => Promise.each(modules, (module) => module.remove())) 
    .then(next) 
    .catch(next)