Nodejs,bcrypt,Mongoose

我对Nodejs / Mongo非常陌生(有Mongoose)。 我正在使用bcrypt模块来从HTML表单中散列密码。 在我的db.create函数中,我无法在mongodb中存储variablesstorehash。

我没有得到任何错误,但在数据库中只是空白。 我已经越过了检查代码的每一行,似乎是工作。 我不明白为什么我不能将variables存储为“password:storehash”,而我被允许存储“password:'test'”之类的东西

我确定我在某个地方做了一些noob错误。 我会很感激任何帮助!

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 

你的db.create应该在console.log(storehash);下面console.log(storehash); ,而不是在bcrypt.salt

当你把它放在bcrypt.salt之后,你所做的是:当你为你的密码生成salt,然后哈希密码,你也使用db.create在你的数据库中存储的东西。 他们同时执行,而不是顺序执行。 这就是为什么,当你哈希你的密码,你也创build一个用户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 } }); });