Farid
Farid

Reputation: 1665

Set required mongoose Schema type to null

I have a registration flow, and the first page only asks for an email and password. The next page asks for country, state (optional), and city.

In my Mongoose model, I have all fields set to required, but country, state, and city are not assigned a value until the second page, so they need to be assigned to null or some other empty or falsy value.

const User = mongoose.Schema({
  email: {
    type: String,
    required: true
  },
  password: {
    type: String
  },
  country: {
    type: String,
    required: true,
  },
  state: {
    type: String,
    default: null,
    required: false,
  },
  city: {
    type: String,
    required: true,
  },
});

How do you assign a null value to a SchemaType in Mongoose when it needs to be a required field?

Upvotes: 2

Views: 5851

Answers (1)

Akrion
Akrion

Reputation: 18525

As per the docs required can be a boolean or a function which should return boolean. So long story short you can create a function which can check if the value is string or null and return true.

Example:

const User = mongoose.Schema({
  email: {
    type: String,
    required: true
  },
  country: {
    type: String,
    required: function() {
      return typeof this.country === 'undefined' || (this.country != null && typeof this.country != 'string')
    }
  }
});

Upvotes: 3

Related Questions