quietplace
quietplace

Reputation: 539

Update email only if it doesn't already exist in mongoDB database

I'm using this route to allow a user to change their email address. However, it currently lets them add an email address that is already used by another user. How can I prevent this (and send an alert in this situation). Also, I'm wondering if .findOneAndUpdate() is appropriate here as it may stop after finding the first one.

Thanks

app.post('/changeUserEmail', function (req, res) {

    db.collection("userDB").findOneAndUpdate(
      {username: req.user.username}, 
      { $set: {email: req.body.newEmail}}, 
      {new: true}, 
      (err, data) => {
      if (err) {
        console.log(err); 
        }
        console.log(null, data);
       }
      )
      res.render(process.cwd() + "/views/options", {
        username: req.user.username,
        email: req.body.newEmail, 
        alert: "Email changed"
      });
});  

Upvotes: 0

Views: 45

Answers (1)

Ilijanovic
Ilijanovic

Reputation: 14904

You could first check if the email exists before you update something

app.post("/changeUserEmail", async function(req, res) {
  let { username } = req.user;
  let { newEmail } = req.body;
  let emailExist = await db.collection("userDB").findOne({ email: newEmail });
  if (emailExist)
    return res.render(process.cwd() + "/views/options", {
      alert: "Email already exists"
    });

  await db
    .collection("userDB")
    .findOneAndUpdate(
      { username },
      { $set: { email: newEmail } },
      { new: true }
    );
  res.render(process.cwd() + "/views/options", {
    username,
    email,
    alert: "Email changed"
  });
});

Upvotes: 1

Related Questions