如何在 2 个属性上使用 bcrypt

问题描述

我在 mongo 项目上使用 bcrypt,我需要在属性密码和电子邮件上使用这个,但我不知道如何在 2 个属性上使用它

exports.signup = (req,res,next) => {
bcrypt.hash(req.body.password,10)
    .then(hash => {
        const user = new User({
            email: req.body.email,password: hash
        });
        user.save()
            .then(() => res.status(201).json({ message: 'Utilisateur créé' }))
            .catch(error => res.status(400).json({ error }));
    })
    .catch(error => res.status(500).json({ error }));
};

感谢您的回答!

解决方法

你可以使用 async/await。还将它包装在 try/catch 块中以进行错误处理。

exports.signup = async (req,res,next) => {
  const email = await bcrypt.hash(req.body.email,10)
  const password = await bcrypt.hash(req.body.password,10)

  const user = new User({
    email: email,password: password
  });

  user.save()
    .then(() => res.status(201).json({
      message: 'Utilisateur créé'
    }))
    .catch(error => res.status(400).json({
      error
    }));
};
,
exports.signup = (req,next) => {
const user = new User();
bcrypt.hash(req.body.email,10)
    .then(hash => {
        user.email = hash
        return bcrypt.hash(req.body.password,10)
    })
    .then(hash => {
        user.password = hash
        return user.save()
    })
    .then(() => res.status(201).json({ message: 'Utilisateur créé' }))
    .catch(error => res.status(500).json({ error }));
};