0

I am a beginner to NodeJs and trying to save user details to mlab, but unable to store hash of password. The hash is calculated and appears in console.log but in mlab document the plaintext is stored instead of hash.

var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var bcrypt = require('bcrypt');

var db = mongojs('mongodb://admin:admin@ds133776.mlab.com:33776/project', 
['users']);

router.get('/',function(req,res,next){
res.render('register.html');
});

router.post('/reguser',function(req,res,next){
var user = req.body;
db.users.findOne({uemail: user.uemail},function(err,xuser){
    if(xuser){
        res.send('User already exists'+JSON.stringify(user));
    }
    else{
        bcrypt.hash(user.upassword,8,function(err,hash){
            user.upassword = hash;
            console.log('hash is '+user.upassword);
        });
        db.users.save(user, function(err,user){
            if(err){
                res.send(err);
            } else {
                console.log('Saved-- '+JSON.stringify(user));
                res.json(user);
            }  
        });
      }
  });
});

1 Answers1

1

It's because the hash function is asynchronous. The execution of the code doesn't follow a straight line. The save function is run before the hash is made in this particular case. If you nest the save inside the hash callback you will create the hash first and then do the saving.

Like this:

bcrypt.hash(user.upassword,8,function(err,hash){
    user.upassword = hash;
    console.log('hash is '+user.upassword);

    db.users.save(user, function(err,user){
        if(err){
            res.send(err);
        } else {
            console.log('Saved-- '+JSON.stringify(user));
            res.json(user);
        }  
    });
});
Mika Sundland
  • 18,120
  • 16
  • 38
  • 50