Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schema.pre in Mongoose modules (NodeJS)

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

This is a middleware function that is called directly before the item is saved to the database (hence the name pre). This makes it possible to execute functions directly before the object is saved. Many times it is used to transform a value.

In this case, before the object is saved, it will hash the password and save that hashed password instead of the plain text version.

next() is a callback that you call when you are done with your function. You can pass an error inside that callback, if you do this, the first error-handling middleware will handle the function and so your item will not be saved to the database.

You can find more information in the docs of Mongoose.

like image 58
Peter Keuter Avatar answered Jun 09 '26 05:06

Peter Keuter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!