Zero
Zero

Reputation: 729

Middleware defined before model definition, cascade delete failing, appears middleware gets bypassed

This is what I have in my file. What I want to do is that when an Author document is removed, all his Book documents should also be removed. I initially experimented with serial middleware with error handlers wired in but no errors were being logged, Author was being removed but his Books were not.

Then I tried parallel middleware under the assumption that remove() won't be triggered until all its pre-middleware has completed but that doesn't seem to be the case. Author is still being removed but Books are not, and no errors are being logged:

//...

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);

So I'm thinking that the middleware is being bypassed otherwise, considering the number of variations that I've tried, I'd have seen at least a couple of errors to indicate that the middleware is indeed being triggered. Unluckily, I just can't seem to put a finger on what I'm doing wrong.

Please advise.

Upvotes: 1

Views: 90

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311955

'remove' middleware only runs when the remove instance method is called (Model#remove), not the class method (Model.remove). This is akin to how 'save' middleware is called on save but not on update.

So you'd need to rewrite your deleteAuthor method to something like:

AuthorSchema.statics.deleteAuthor = function(authorId, callback) {
    this.findById(authorId, function(err, author) {
        if (author) {
            author.remove(callback);
        } else {
            callback(err);
        }
    });
};

Upvotes: 1

Related Questions