首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Nodejs,bcrypt,Mongoose

Nodejs,bcrypt,Mongoose
EN

Stack Overflow用户
提问于 2017-06-20 14:13:57
回答 1查看 433关注 0票数 1

我对Nodejs / Mongo (和猫鼬)非常陌生。我使用bcrypt模块从HTML表单中散列密码。在我的db.create函数中,我无法将变量存储散列存储在mongodb中。

我没有发现任何错误,但它只是数据库中的空白。我已经检查了代码的每一行,它似乎正在工作。我不明白为什么不能将变量存储为“密码:存储散列”,而不允许存储诸如“密码:‘测试’”之类的内容

我肯定我在某个地方犯了什么错误。我很感谢你的帮助!

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-20 14:32:11

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

当您将其放在bcrypt.salt之后时,您所做的是:当您为密码生成salt,然后哈希加密密码时,您还使用db.create将内容存储在数据库中。它们是同时执行的,而不是顺序执行的。这就是为什么,当您正在哈希密码时,您还创建了一个没有密码的db.create 的用户

换言之,它应该是:

代码语言:javascript
复制
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
        }
    });

}); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44655510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档