[英]MongoDB stores “Promise” object instead of hashed password
I am using bcrypt to hash passwords and MongoDB as my database.我使用 bcrypt 到 hash 密码和 MongoDB 作为我的数据库。
Here is the code:这是代码:
export default function buildMakeUser({pwdHasher})
{
return function makeUser({
username,
email,
password,
password_hash = pwdHasher(password), // the important part
favoriteColor
} = {})
{
// ...
return Object.freeze({
getUsername: () => username,
getEmail: () => email,
getHashedPassword: () => password_hash,
getFavoriteColor: () => favoriteColor
});
}
And here is pwdHasher
's definition:这是
pwdHasher
的定义:
import bcrypt from "bcrypt";
import buildMakeUser from "./entity/user.js";
async function pwdHasher(password){
let hashed;
hashed = await bcrypt.hash(password, 10);
return hashed;
}
However, when I store the user in the database, here's the result:但是,当我将用户存储在数据库中时,结果如下:
ops: [
{
username: 'kibe',
email: 'blabla@gmail.com',
password_hash: [Promise],
_id: 5ecc8b752e0aa53e87d5b62a
}
],
It seems like makeUser
's object does not wait for pwdHasher(password)
.似乎
makeUser
的 object 不等待pwdHasher(password)
。 I have tried wrapping pwdHasher
in a Promise and it also did not work.我曾尝试将
pwdHasher
包装在 Promise 中,但它也没有用。
Does anyone know why?有谁知道为什么?
Thank you.谢谢你。
There are two solutions I see based on your code snippet:根据您的代码片段,我看到了两种解决方案:
First way: (Recommended)第一种方式:(推荐)
Use await
when calling the async
function.调用
async
function 时使用await
。 The code will be:代码将是:
export default function buildMakeUser({pwdHasher})
{
return function makeUser({
...
password_hash = await pwdHasher(password), // the important part
...
})
}
Alternative way:替代方式:
Use hashSync
method of bcrypt
instead of using async-await.使用
bcrypt
的hashSync
方法而不是使用 async-await。
You have defined pwdHasher
as:您已将
pwdHasher
定义为:
async function pwdHasher(password) { ... }
But you call it as:但你称它为:
password_hash = pwdHasher(password),
By definition, an async function RETURNS A PROMISE.根据定义,异步 function 返回 PROMISE。 If you'd like to get the value from the promise, you must either
await
the result or use pwdHasher(password).then(...)
如果您想从 promise 获取值,您必须
await
结果或使用pwdHasher(password).then(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.