Home > Net >  How to check if Email exists , throw error if so , and create user if no match with Sequelize and Ex
How to check if Email exists , throw error if so , and create user if no match with Sequelize and Ex

Time:02-06

I am trying to check if the req.body.email already exists in the db, then I would like to throw error, if not in the db , then try and create my user... But this is failing its only returning email is in system even if i change the email can anyone help me with this one please ?

const User = require("../models/users");

const createSingleUser = async (req, res) => {
  // we need to make sure the provided email is not being used if it exists in the db
  // them we through an error if not then we create the user
  // step one lets search by the email provided
  const checkEmail = req.body.email;
  const found = await User.findOne({
    where: {
      email: checkEmail,
    },
  });
  // if found is not empty meaning a match was found
  if (found != "") {
    res.send("this email is already in system");
  } else {
    // create the user since its empty no match found
    try {
      const newUser = await User.create({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        dateOfBirth: req.body.dateOfBirth,
        email: req.body.email,
        phone: req.body.phone,
      });
      User.sync({ alter: true });
      res.send(await newUser);
    } catch (err) {
      res.send(err);
    }
  }
};

module.exports = createSingleUser;

CodePudding user response:

You should also give us a log of what found contains, but with a guess maybe try changing this line:

if (found != "") 

to line below:

if (found)
  •  Tags:  
  • Related