Mongoose pre.save() async middleware not working as expected

后端 未结 1 1684
有刺的猬
有刺的猬 2021-02-01 05:19

Following up from : Mongoose unique validation error type

I\'m using this schema with mongoose 3.0.3 from npm:

var schema = new Schema({

           


        
相关标签:
1条回答
  • 2021-02-01 05:54

    You're using a parallel middleware callback function (with both next and done), but you're not setting the parallel flag in the schema.pre parameters so it's using the serial rules.

    So either include the parallel flag in your call:

    schema.pre("save", true, function(next, done) { ...
    

    Or switch to a serial middleware callback style if that's all you need anyway:

    schema.pre("save", function(next) {
        var self = this;
    
        model.findOne({email : this.email}, 'email', function(err, results) {
            if(err) {
                next(err);
            } else if(results) {
                console.warn('results', results);
                self.invalidate("email", "email must be unique");
                next(new Error("email must be unique"));
            } else {
                next();
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题