Xaarth
Xaarth

Reputation: 1151

How to check if email already exists excluding the current record mongoose

I have created an update route for a product. there are some fields that must be unique.

when creating a product I'm checking that like so

const emailExists = await Foodlancer.findOne({ email: values.email });

if (emailExists) {
  return res.status(400).json({ error: 'Email already used' });
}

But I'm not sure how to check if email is already used when updating a product.

If I use the code above it returns true for the same object that we are updating.

Is there a way to exclude an object? I have looked at $ne and $nin but not sure how to use them in this case.

Any suggestions?

Upvotes: 2

Views: 1502

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

Firstly you could create a unique index and enforce this at the database level. this would not let you insert or update an email that exists in the system.

Regarding the logic check you want to do, why not just use the same code for creation on the update with the addition of checking if the _id is different with $ne

(I'm assuming you're updating with a document _id otherwise you would have just used the actual email for the update?)

const documentToUpdateId = new ObjectId(req.body._id);
const emailExists = await Foodlancer.findOne({ email: req.body.email, _id: {$ne: documentToUpdateId}});

if (emailExists) {
  return res.status(400).json({ error: 'Email already used' });
}

Upvotes: 4

Related Questions