Mongodb 用户架构错误
Mongodb user schema error
我正在尝试使用邮递员发送数据并创建我的用户。但我一直收到错误,所以我注释掉了一些实际上不需要的代码,现在我收到了这个错误。有谁知道我可能做错了什么?
Mongodb 已连接,服务器 运行 在端口 3000 上。
错误表明您向 bcrypt.hash()
传递了一个无效参数,即 undefined
而不是密码。检查是否定义了 req.body.password
。
确保在 addUser 函数中捕获 newUser.password 之前创建 console.log(newUser)。在使用数据启动新的用户模式后,对象没有像您期望的那样出现。或者简单地给出一个你自己的字符串来进行盐传递,然后检查它是否正常工作。
正如 @Joe and @robertklep 已经提到的,您在第 63 行中有错误:
bcrypt.hash(newUser.password, salt, (err, hash => {
因为变量 password 是 undefined。
尝试手动定义它并确保您编写的代码正确执行。
但我强烈建议您仔细查看 at virtual field (in mongoose) 并使用它来生成 salt 密码。
在您的情况下,您可以使用 mongoose 和 bcrypt 使用此代码片段完成相同的工作。
//首先,在您的架构中将 "password" 重命名为 "clean_password"
user.virtual('clean_password')
.set(function(clean_password) {
this._password = clean_password;
this.password = this.encryptPassword(clean_password);
})
.get(function() {
return this._password;
});
user.methods = {
/**
* Authenticate - check if the passwords are the same
*
* @param {String} plainText
*/
authenticate: function(plainPassword) {
return bcrypt.compareSync(plainPassword, this.password);
},
/**
* Encrypt password
*
* @param {String} password
*/
encryptPassword: function(password) {
if (!password)
return '';
return bcrypt.hashSync(password, 10);
}
};
并通过以下方式检查:
var user = {
username: "whateveryouwant",
clean_password: "whateveryouneed"
}
User.create(user, function(err,doc){});
我正在尝试使用邮递员发送数据并创建我的用户。但我一直收到错误,所以我注释掉了一些实际上不需要的代码,现在我收到了这个错误。有谁知道我可能做错了什么?
Mongodb 已连接,服务器 运行 在端口 3000 上。
错误表明您向 bcrypt.hash()
传递了一个无效参数,即 undefined
而不是密码。检查是否定义了 req.body.password
。
确保在 addUser 函数中捕获 newUser.password 之前创建 console.log(newUser)。在使用数据启动新的用户模式后,对象没有像您期望的那样出现。或者简单地给出一个你自己的字符串来进行盐传递,然后检查它是否正常工作。
正如 @Joe and @robertklep 已经提到的,您在第 63 行中有错误:
bcrypt.hash(newUser.password, salt, (err, hash => {
因为变量 password 是 undefined。 尝试手动定义它并确保您编写的代码正确执行。
但我强烈建议您仔细查看 at virtual field (in mongoose) 并使用它来生成 salt 密码。
在您的情况下,您可以使用 mongoose 和 bcrypt 使用此代码片段完成相同的工作。
//首先,在您的架构中将 "password" 重命名为 "clean_password"
user.virtual('clean_password')
.set(function(clean_password) {
this._password = clean_password;
this.password = this.encryptPassword(clean_password);
})
.get(function() {
return this._password;
});
user.methods = {
/**
* Authenticate - check if the passwords are the same
*
* @param {String} plainText
*/
authenticate: function(plainPassword) {
return bcrypt.compareSync(plainPassword, this.password);
},
/**
* Encrypt password
*
* @param {String} password
*/
encryptPassword: function(password) {
if (!password)
return '';
return bcrypt.hashSync(password, 10);
}
};
并通过以下方式检查:
var user = {
username: "whateveryouwant",
clean_password: "whateveryouneed"
}
User.create(user, function(err,doc){});