0

I use bcrypt on mongo project, i need to use this one on properties Password and email, but I don't know how to use it on 2 properties

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 }));
};

Thanks for your answers !

2 Answers2

1

You can use async/await for that. Also wrap it it in try/catch blocks for error handling.

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
    }));
};
dako
  • 1,081
  • 1
  • 12
  • 22
  • 1
    Good answer, you should also convert `user.save().then()` to `await user.save()` to be consistent with the coding style. – Jeremy Thille Mar 10 '21 at 11:00
  • Yeah, no worries, it's just not in the scope of the question in my opinion. But I guess you're right about the extra mile :) – dako Mar 10 '21 at 11:06
  • Indeed, it's not, you're right. But I would have done it. That's why I encouraged you to go the extra mile, it would teach OP to write better and more consistent code. It's the kind of little details that make me decide whether or not I hire the dev :) Bah, have the upvote regardless! – Jeremy Thille Mar 10 '21 at 11:09
  • Thanks. I totally agree with you. I can always edit it like how you suggested, but I consider it not fair to steal your idea and present it as mine in the answer. – dako Mar 10 '21 at 11:16
0
exports.signup = (req, res, 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 }));
};