“前置"和“发布"删除中间件不触发 [英] "pre" and "post" remove Middleware not firing

查看:95
本文介绍了“前置"和“发布"删除中间件不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了两种删除用户的方法,但没有一种触发"pre"和"post"删除中间件.

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

据我了解

下面是我的模型文件中的两个不同实现:

Below are my two different implementations in my model file:

方法一:

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

}

方法二:

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

这篇关于“前置"和“发布"删除中间件不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆