Search code examples
javascriptnode.jsmongodbmongoose

What is the proper way to validate email uniqueness with mongoose?


I cannot find a proper way to provide validation for email uniqueness in mongoose. Nothing I have found actually works. I was thinking to use Schema.pre, but how would I go about writing the code for that if that is the case? The Mongoose documentation is very poor and does not describe how or what pre does.

I would appreciate it if somebody could tell me how this is normally done or point me in the right direction. I don't understand why something so simple has no simple solution in mongoose...


Solution

  • You could use a custom validator:

    var userSchema = new Schema({
      email: {
        type: String,
        validate: {
          validator: async function(email) {
            const user = await this.constructor.findOne({ email });
            if(user) {
              if(this.id === user.id) {
                return true;
              }
              return false;
            }
            return true;
          },
          message: props => 'The specified email address is already in use.'
        },
        required: [true, 'User email required']
      }
      // ...
    });