These are chat archives for Automattic/mongoose

21st
Aug 2016
brandonjfajardo
@brandonjfajardo
Aug 21 2016 16:24
what does this mean? if (err){ return next(err) }
if there's an error call the next middleware and pass the error? why would u want to pass the error
Vlado Tesanovic
@vladotesanovic
Aug 21 2016 16:50
@brandonjfajardo that is express thing not mongoose :)
brandonjfajardo
@brandonjfajardo
Aug 21 2016 16:51
couldn't you just resolve the error in the if statement then call next() ?
because i am hashing passwords before the user gets saved
userSchema.pre('save', (next) => {
bcrypt.genSalt(10, (err, salt) => {
if (err){
return next(err);
......
Vlado Tesanovic
@vladotesanovic
Aug 21 2016 16:52
i have similar code somewhere, give me sec
brandonjfajardo
@brandonjfajardo
Aug 21 2016 16:53
okay thanks
Vlado Tesanovic
@vladotesanovic
Aug 21 2016 16:53
you just pass error to next function in chain, than that function should handle it
@brandonjfajardo
/**
 * Pre save function on user collection.
 * Hash password for new users.
 *
 * @param next
 */
export function preSave(next: (err: Error, data?: IUserDocument) => void): void {

    const user: IUserDocument = this;

    // only if user is new or password is changed
    hashPassword(user.password)
        .then((data: IHashedPassword) => {

            user.password = data.hash;
            user.salt = data.salt;

            return next(undefined, user);
        });
}
brandonjfajardo
@brandonjfajardo
Aug 21 2016 16:54
what are the use cases for that though
isn't the idea to handle it right away where there is an error
Vlado Tesanovic
@vladotesanovic
Aug 21 2016 16:54
that is my function, Typescript but just remove types