Home > front end >  How can I catch Error from Node.js user Model
How can I catch Error from Node.js user Model

Time:12-15

In the user model schema, I give first_name to require and email to unique and require, when I save the data in the database I would like to send a response if the user will not send the first_name. how can we do this without add manually conditions?

I'm adding manually conditions for this operation

exports.saveuser = async (req, res) => {
  const { first_name, email } = req.body;

  if (!first_name || !email)
    return res.status(401).json({ error: 'All the data require' });

  const user = User.findOne({ email });

  if (user) {
    return res.status(401).json({ error: 'Email already exist' });
  }

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

  await user.save();
};

in the above code, I add conditions manually, but I don't want to add all the conditions every time.

CodePudding user response:

You can follow express Validator. It pretty industry standard. https://express-validator.github.io/docs/ Below is the example:

  router.PUT(
    `/api/user`,
    auth,
    validate(UserValidator.saveUser),
    UserController.saveUser,
  );
  • Related