Search code examples
node.jsmongoose

Validation in mongoose Schema


I am writing validations for user schema entries in mongoose. I want to make any one of two entries (password, googleId) required in the schema, but not both the entries are required. I want to make sure that user have either password or googleId. How this can be done? Following is me Schema

const UserSchema = new mongoose.Schema({
    password: {
        type: String,
        trim: true,
        required: true,
        validate: (value)=>
        {
            if(value.includes(this.uname))
            {
                throw new Error("Password must not contain username")
            }
        }
    },
    googleId: {
        type: String,
        required: true
    }
});


Solution

  • You could use a custom validator :

    const UserSchema = new mongoose.Schema({
        password: {
            type: String,
            trim: true,
            required: true,
            validate: {
                validator: checkCredentials,
                message: props => `${props.value} is not a valid phone number!`
            },
        },
        googleId: {
            type: String,
            required: true
        }
    });
    
    
    function checkCredentials(value) {
       if (!this.password || !this.googleId) {
           return false;
       }
       return true; 
    }
    
    
    
    

    Or with a pre validation middleware

    UserSchema.pre('validate', function(next) {
        if (!this.password || !this.googleId) {
            next(new Error('You should provide a google id or a password'));
        } else {
            next();
        }
    });