0
votes

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
    }
});

2

2 Answers

0
votes

What you could probably do is to add a pre validate check and then either call next or invalidate the document.

const schema = new mongoose.Schema({
    password: {
        type: String,
        trim: true
    },
    googleId: {
        type: String
    }
});

schema.pre('validate', { document: true }, function(next){
    if (!this.password || !this.googleId)
        this.invalidate('passwordgoogleId'. 'One of the fields required.');
    else
        next();
});

I haven't tried it though.

0
votes

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();
    }
});