这就是我在文件中的内容。我想要做的是,当删除Author
文档时,他的所有Book
文档也应该被删除。我最初尝试使用连接了错误处理程序的串行中间件,但没有记录错误,Author
被删除,但他的Book
没有。
然后我尝试并行中间件假设remove()
在所有预中间件完成之前不会被触发,但似乎并非如此。 Author
仍在删除,但Book
未被删除,并且未记录任何错误:
//...
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);
所以我认为中间件正在被绕过,否则,考虑到我尝试过的变种数量,我至少看到了几个错误,表明中间件确实被触发了。不幸的是,我似乎无法指责我做错了什么。
请告知。
答案 0 :(得分:1)
'remove'
中间件仅在调用remove
实例方法(Model#remove
)时运行,而不是类方法(Model.remove
)。这类似于在'save'
上调用save
中间件而在update
上调用的方式。
因此,您需要将deleteAuthor
方法重写为:
AuthorSchema.statics.deleteAuthor = function(authorId, callback) {
this.findById(authorId, function(err, author) {
if (author) {
author.remove(callback);
} else {
callback(err);
}
});
};