模型定义之前定义的中间件,级联删除失败,出现中间件被绕过
这是我在我的文件中。 我想要做的是当一个Author
文档被删除,他所有的Book
文档也应该被删除。 我最初尝试使用连接error handling程序的串行中间件,但没有错误logging, Author
被删除,但他的Book
没有。
然后我尝试了并行中间件,假设remove()
不会被触发,直到所有的前中间件都完成了,但似乎并不是这样。 Author
仍被删除,但Book
没有,也没有错误logging:
//... var Book = require('./book-model''); AuthorSchema.pre('remove', true, function(next, done) { Book.remove({author: this._id}, function(err) { if (err) { console.log(err); done(err); } done(); }); next(); }); AuthorSchema.statics.deleteAuthor = function(authorId, callback) { var Author = mongoose.model('Author'); Author.remove({_id: authorId}, callback); }; // ... module.exports = mongoose.model('Author', AuthorSchema);
所以我在考虑中间件被绕过,否则考虑到我尝试过的变化的数量,我会看到至less有一些错误,表明中间件确实被触发。 不幸的是,我似乎无法指出我做错了什么。
请指教。
'remove'
中间件只在调用remove
实例方法时运行( Model#remove
),而不是类方法( Model.remove
)。 这类似于如何在save
调用中间件而不是在update
调用中间件。
所以你需要重写你的deleteAuthor
方法,如下所示:
AuthorSchema.statics.deleteAuthor = function(authorId, callback) { this.findById(authorId, function(err, author) { if (author) { author.remove(callback); } else { callback(err); } }); };