Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
How do I check email in backend register

I have a problem with my code now and I can't make it work. I am trying to check if the email added by the user is already in the database so I can generate an error message to the person and I don't know exactly how to check this. Can someone please help me? Thank you so much

Backend code now:

//Create user
app.post("/register/users", (req, res, next) => {
  let userData = {
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  };
  const user = new User(userData);
  user
    .save()
    .then((result) => {
      res.status(200).json(result._id);
    })
    .catch((error) => res.status(422).json(error));
  // console.log(res.body);
});

How can I check if user with similar email is already register to display the error? Thank you so much for your time

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can do a check before saving the user.

First, check if the user with the same email exists in the database. If exist, do not save again, instead send the response. If not exist, save the user.

app.post("/register/users", async (req, res, next) => {
  let userData = {
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  };
  // checkin if a user with the mail exist
  try {
    const existingUser = await User.findOne({ email: req.body.email });
    if (existingUser) {
      // you may want to send different status code
      return res.status(200).json({ message: 'User alreay registered });
    }
    const user = new User(userData);
    // save the user
    const newUser = await user.save();
    return res.status(200).json(newUser._id);
  } catch(error) {
    return res.status(422).json({ error });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!