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

问题描述 投票:5回答:3

我已经实现了两种不同的方法来删除用户,而不是其中一种方法触发“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);
}

任何建议将不胜感激。

node.js mongodb mongoose middleware
3个回答
10
投票

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

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

5
投票

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


2
投票

其他任何寻找相同的人。 deleteOne和deleteMany中间件可以与pre和post中间件一起使用。删除已从最新的mongo版本中弃用。

下面的代码让事情对我有用。

   ModelSchema.pre("deleteOne", { document: true }, function(next) {
      let id = this.getQuery()["_id"];
      mongoose.model("Model_two").deleteMany({ property: id }, function(err, result) {
        if (err) {
          next(err);
        } else {
          next();
        }
      });
    });
© www.soinside.com 2019 - 2024. All rights reserved.