node.js - Nodejs、bcrypt、 Mongoose

标签 node.js mongodb mongoose bcrypt

我对 Nodejs/Mongo(与 Mongoose)非常陌生。我正在使用 bcrypt 模块对 HTML 表单中的密码进行哈希处理。在我的 db.create 函数中,我无法将变量 storehash 存储在 mongodb 中。

我没有收到任何错误,但它在数据库中只是空白。我已经交叉检查了代码的每一行,它似乎有效。我不明白为什么我不能将变量存储为“password: storehash”,而允许存储类似“password: 'test'”的内容

我确信我在某个地方犯了一些菜鸟错误。如果有任何帮助,我将不胜感激!

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);的正下方,而不是在bcrypt.salt之后。

当您将其放在 bcrypt.salt 之后时,您要做的是:在为密码生成 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
        }
    });

}); 

关于node.js - Nodejs、bcrypt、 Mongoose ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44655510/

相关文章:

javascript - Mongoose 填充数组为空

node.js - Node JS-检查mongoDB中是否存在字段

javascript - MongoDB 简单时间序列

Spring Data MongoDB,如何设置SSL?

javascript - Mongoose 是否可以至少拥有一项所需的属性?

javascript - 如何正确使用promise的resolve和reject

node.js - 将 jade 变量分配给 Angular

mysql - Node Mysql 异步多个查询

javascript - Mongoose 模型 : calculate and automatically update average rating

mongodb - 如何在子属性上使用 $setIsSubset (或其他集合操作)