Le Rajk Le Rajk - 1 month ago 7
Node.js Question

Nodejs, bcrypt , Mongoose

I'm very new to Nodejs / Mongo (with Mongoose). I'm using the bcrypt module to hash the password from a HTML form. In my db.create function, I'm not able to store the variable storehash in mongodb.

I don't get any errors but its just blank in the database. I have crossed check every other line of the code and it seems to be working. I don't understand why I'm not able to store a variable as "password: storehash" whereas I'm allowed to store something like "password: 'test' "

I'm sure I'm making some noob mistake somewhere. I'd appreciate any help!



var db = require('../models/users.js');
var bcrypt = require('bcryptjs');


module.exports.createuser = function(req,res){

var pass = req.body.password;
var storehash;

//passsord hashing
bcrypt.genSalt(10, function(err,salt){
if (err){
return console.log('error in hashing the password');
}
bcrypt.hash(pass, salt, function(err,hash){
if (err){
return console.log('error in hashing #2');
} else {

console.log('hash of the password is ' + hash);
console.log(pass);
storehash = hash;
console.log(storehash);
}
});

});

db.create({

email: req.body.email,
username: req.body.username,
password: storehash,


}, function(err, User){
if (err){
console.log('error in creating user with authentication');
} else {
console.log('user created with authentication');
console.log(User);
}
}); //db.create


};// createuser function




Answer Source

Your db.create should go right below console.log(storehash);, not after the bcrypt.salt.

When you put it after bcrypt.salt, what you do is: while you're generating salt for your password and then hashing the salted password, you're also storing stuff in your database using db.create. They are executed simultaneously, not sequentially. That's why, while you're hashing your password, you're also creating a user with db.create without a password.

In other words, it should be:

bcrypt.genSalt(10, function(err,salt){
    if (err){ 
        return console.log('error in hashing the password');
    } 
    bcrypt.hash(pass, salt, function(err,hash){
        if (err){
            return console.log('error in hashing #2');
        } else {

            console.log('hash of the password is ' + hash);
            console.log(pass);
            storehash = hash; 
            console.log(storehash);
            db.create({

                email: req.body.email,
                username: req.body.username,
                password: storehash,


            }, function(err, User){
                if (err){ 
                    console.log('error in creating user with authentication');
                } else {
                    console.log('user created with authentication');
                    console.log(User);
                }
            }); //db.create
        }
    });

});