在模型定义之前定义的中间件,级联删除失败,出现中间件被绕过

时间:2014-10-15 21:01:51

标签: node.js mongodb express mongoose

这就是我在文件中的内容。我想要做的是,当删除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);

所以我认为中间件正在被绕过,否则,考虑到我尝试过的变种数量,我至少看到了几个错误,表明中间件确实被触发了。不幸的是,我似乎无法指责我做错了什么。

请告知。

1 个答案:

答案 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);
        }
    });
};