1

I have a user schema with unique: true and the following validator:

          { // checks if email already used
                validator: async (value) => {
                    let user = await mongoose.model('User').findOne({ email: value });
                    return !user;
                },
                message: 'Email already exists'
            }

It works as expected when creating a new user, the problem is with updating. I'm using doc.save() to update a user documents (it's a valid way to update documents according to Mongoose documentation). but that validator is being triggered again. Is there a way to use the save methods without triggering that validator again?

Thanks.

dor272
  • 550
  • 1
  • 6
  • 26

1 Answers1

1

i was looking it up and actually found a Stackoverflow thread here.

Basically how I understand it:

While using .save() the validators are always triggered, but on the other hand using .update() doesn't (unless you specify it in the options).

Maybe try using update instead? (I know this is not a 100% answer, just trying to help)

EDIT: As discussed you can always add specific validators into your controller instead in your Schemas.

  • That's an option but I have other validators I want run. – dor272 Sep 13 '20 at 07:51
  • What you could do is => Add the validation of your email address to your controller (express route e.g.) instead of the Schema this way you can control if you want to save the new document –  Sep 13 '20 at 08:35
  • That's what I ended up with.. :) – dor272 Sep 13 '20 at 14:36
  • Always appreciate an upvote since I can't even like anything myself :D –  Sep 13 '20 at 15:02