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);
}
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);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With