2017-06-20 75 views
1

我很新Nodejs/Mongo(与猫鼬)。我正在使用bcrypt模块来从HTML表单中散列密码。在我的db.create函数中,我无法在mongodb中存储变量storehash。Nodejs,bcrypt,Mongoose

我没有得到任何错误,但它只是在数据库中空白。我已经检查了代码的其他所有行,它似乎正在工作。我不明白为什么我无法将变量存储为“password:storehash”,而我被允许存储类似“password:'test'”的变量“

我确信我正在做一些noob错误的地方。我会很感激任何帮助!

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

 

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

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

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

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

 
\t }); 
 

 
db.create({ 
 

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

 

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

 

 
};// createuser function

+0

代码示例! – num8er

+0

使用SO提供的代码格式化程序不发布代码的图像 –

+0

哈哈我想我只是做到了这一点。谢谢! –

回答

1

db.create应该去右下方console.log(storehash);,在bcrypt.salt后不。

当你把它放在bcrypt.salt之后时,你要做的是:当你为你的密码产生盐然后散列咸味的密码时,你也使用db.create在你的数据库中存储东西。他们同时执行,而不是顺序执行。这就是为什么,当你在密码中加密时,你还会创建一个db.create而没有密码的用户。

换句话说,它应该是:

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 
     } 
    }); 

}); 
+0

哦,是的!对。得到它了。我相信我混合了节点异步性质的同步编程。 它现在工作。非常感谢 !! –