Schema.pre in Mongoose modules (NodeJS)

Viewed 754

I'm getting started with NodeJS and i'm currently working on a nice tutorial i found on the internet to manage authentication: https://devdactic.com/restful-api-user-authentication-1/

There is a block of code i don't really understand and i can't find further explanations on the internet, even on the official page of the module...

UserSchema.pre('save', function (next) {
    var user = this;
    if (this.isModified('password') || this.isNew) 
    {
        bcrypt.genSalt(10, function (err, salt) 
        {       
            if (err) 
            {
                return next(err);
            }
            bcrypt.hash(user.password, salt, function (err, hash) {
                if (err) {
                    return next(err);
                }
                user.password = hash;
                next();
            });
        });
    } 
    else 
    {
        return next();
    }
});

In this block of code, what is "pre", i think they call that a hook but i don't understand what it means. Afterwards there is also a callback function taking as parameter "next" but i thought the first parameter in a callback function was always "error". If someone can put some light on that block of code, i would really appreciate...Thanks in advance

1 Answers
Related