Home > Blockchain >  Setting mongoose to allow null without breaking validation
Setting mongoose to allow null without breaking validation

Time:08-09

Here is how my application works. A user logs in for the first time using Google Sign in. We get the following data from their Google Account:

  1. Given name
  2. Family name
  3. Email ID

We wish to use this information to call our API (POST request) to create a user profile.

The data we send is

{
firstName: firstName ,
lastName: lastName, 
email: email
}

Here is where the issue comes from. The user profile has many fields and one of them is designation. When the user logs in for the first time, we don't know their designation.

We are using MongoDB for our database. So we use Mongoose to set up the connection. In Mongoose model, we have added some validation for our schema. Designation is a required field. It should be at least one character of length and maximum of 40 characters. If we set designation as null, the validation would fail.

Is there any way to allow null in a required field in Mongoose?

CodePudding user response:

Rather than setting required to true or false, you can pass it a function:

const user = new Schema({
  designation: {
    type: String,
    minLength: 1,
    maxLength: 40,
    required: function() {
      // Rather than checking a stored variable, you could check
      // static functions on the model, a custom value on the 
      // instance that isn't persisted, etc.
      return this.hasLoggedInAtLeastOnce === true;
      // If this function returns true, the field is required.
    }
  }
  hasLoggedInAtLeastOnce: {
    type: Boolean,
  }
});
  • Related