"pre" and "post" remove Middleware not firing "pre" and "post" remove Middleware not firing mongoose mongoose

"pre" and "post" remove Middleware not firing


This is how I got everything working:

// Remove Usermodule.exports.removeUser = function(id, callback){    User.findById(id, function (err, doc) {        if (err) {        }        doc.remove(callback);    })}//Remove vouchers related to usersuserSchema.pre('remove', function(next) {    this.model('Voucher').remove({ user: this._id }, next);});


http://mongoosejs.com/docs/middleware.htmlPlease refer to the documentation. By design the middleware hook for remove is not fired for Model.remove, only for ModelDocument.remove function.


For anyone having the issue in future, check that you defined your hooks before calling mongoose.model().

Define Middleware Before Compiling Models

Calling pre() or post() after compiling a model does not work in Mongoose in general. For example, the below pre('save') middleware will not fire.

...

https://mongoosejs.com/docs/middleware.html#defining