Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"pre" and "post" remove Middleware not firing

I have implemented two different ways to remove a user and not one of them fires the "pre" and "post" remove Middleware.

As I understand

Below are my two different implementations in my model file:

Method One:

var User = module.exports = mongoose.model('User', userSchema);

userSchema.pre('remove', function(next) {
    // 'this' is the client being removed. Provide callbacks here if you want
    // to be notified of the calls' result.
    //Vouchers.remove({user_id: this._id}).exec();
    console.log("pre test");
    next();
});

userSchema.post('remove', function(next) {
    // 'this' is the client being removed. Provide callbacks here if you want
    // to be notified of the calls' result.
    //Vouchers.remove({user_id: this._id}).exec();
    console.log("post test");
    next();
});

// Remove User
module.exports.removeUser = function(id, callback){
    var query = {_id: id};
    console.log('test');
    //User.remove(query, callback);
    User.find(query).remove(callback);

}

Method Two:

var User = module.exports = mongoose.model('User', userSchema);

userSchema.pre('remove', function(next) {
    // 'this' is the client being removed. Provide callbacks here if you want
    // to be notified of the calls' result.
    //Vouchers.remove({user_id: this._id}).exec();
    console.log("pre test");
    next();
});

userSchema.post('remove', function(next) {
    // 'this' is the client being removed. Provide callbacks here if you want
    // to be notified of the calls' result.
    //Vouchers.remove({user_id: this._id}).exec();
    console.log("post test");
    next();
});

// Remove User
module.exports.removeUser = function(id, callback){
    var query = {_id: id};
    console.log('test');
    User.remove(query, callback);
}
like image 503
Siegfried Grimbeek Avatar asked Dec 25 '15 17:12

Siegfried Grimbeek


2 Answers

This is how I got everything working:

// Remove User
module.exports.removeUser = function(id, callback){

    User.findById(id, function (err, doc) {
        if (err) {

        }

        doc.remove(callback);
    })
}

//Remove vouchers related to users
userSchema.pre('remove', function(next) {
    this.model('Voucher').remove({ user: this._id }, next);
});
like image 190
Siegfried Grimbeek Avatar answered Nov 15 '22 13:11

Siegfried Grimbeek


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

like image 31
Yerken Avatar answered Nov 15 '22 13:11

Yerken