0

I am writing code in Node.js to encrypt passwords using bcrypt.

However, if you use bcrypt, you will get an ValidationError: User validation failed: password: Cast to String failed for value "Promise { <pending> }" at path "password"

I do not get this error if I save it as plain text without encryption.

Is there a secret of bcrypt I do not know?

bcrypt (not working)

const bcrypt = require('bcrypt');

sign_up = (req, res, next) => {
  const { email, password } = req.body;
  const User = User.findOne({ email: email });
  if (exUser) {
    return res.send('exist user');
  }
  const hash = bcrypt.hash(password, 8);
  const user = new User({
    email: email,
    password: hash
  });

  user.save((err) => {
    if (err) {
      return next(err);
    }
    res.send('signup success');
  });
};

no bcrypt (working)

sign_up = (req, res, next) => {
  const { email, password } = req.body;
  const User = User.findOne({ email: email });
  if (exUser) {
    return res.send('exist user');
  }
  const user = new User({
    email: email,
    password: password
  });

  user.save((err) => {
    if (err) {
      return next(err);
    }
    res.send('signup success');
  });
};
1

1 Answer 1

1

To elaborate on Chris's comment:

It appears that bcrypt.hash is asynchronous, and is returning a Promise.

To fix this, I would recommend using an async function and awaiting the result. MDN page

This may require a newer version of NodeJS than what you are running.

const bcrypt = require('bcrypt');

// Async function allows us to use await
sign_up = async (req, res, next) => {

  const { email, password } = req.body;
  const User = User.findOne({ email: email });
  if (exUser) {
    return res.send('exist user');
  }

  // We await the result of the hash function
  const hash = await bcrypt.hash(password, 8);

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

  user.save((err) => {
    if (err) {
      return next(err);
    }
    res.send('signup success');
  });
};

Do not use the bcrypt.hashSync function, as while it is running your server will not be able to do anything else.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.