简体   繁体   中英

mocha test fail because this is undefined in mongoose pre validate hooks model (even without arrow function)

I'm testing a post request that basically registers users to db. my mocha test fails because this is undefined when the pre validate hooks is triggered. I'm already using a normal function instead of an arrow function. It works perfectly in postman/insomnia . the problem occurs if I'm testing it through mocha.

userSchema.pre('validate', function(next) {

    if (this.password.split(' ').length > 1) {
        next(new Error('password can not contain a white space'));
    } else {
        next();
    }
});

For access to this it should be separate function

function preValidateFunction(next) {
    if (this.password.split(' ').length > 1) {
        next(new Error('password can not contain a white space'));
    } else {
        next();
    }
}

userSchema.pre('validate', preValidateFunction);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM