2017-06-20 71 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

哦,是的!對。得到它了。我相信我混合了節點異步性質的同步編程。 它現在工作。非常感謝 !! –