当前位置:  开发笔记 > 编程语言 > 正文

猫鼬 - "前"和"后"删除中间件没有开火

如何解决《猫鼬-"前"和"后"删除中间件没有开火》经验,为你挑选了2个好方法。

我已经实现了两种不同的方法来删除用户,而不是其中一种方法触发"pre"和"post"删除中间件.

我认为

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

方法一:

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

任何建议将不胜感激.



1> Siegfried Gr..:

这就是我让一切工作的方式:

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


你的回答根本没有帮助我.我还可以将人们指向文档并告诉他们自己弄清楚.我试着详细说明并解释在回答问题时的原因和原因,因此我会相应地进行投票.我发现任何人都可以浏览文档并引用人员.

2> Yerken..:

http://mongoosejs.com/docs/middleware.html 请参阅文档.按照设计,Model.remove不会触发用于remove的中间件钩子,仅适用于ModelDocument.remove函数.


Note: There is no query hook for remove(), only for documents. If you set a 'remove' hook, it will be fired when you call myDoc.remove(), not when you call MyModel.remove()
推荐阅读
mobiledu2402851323
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有