Is it possible to have at least one property required in Mongoose? Is it possible to have at least one property required in Mongoose? mongoose mongoose

Is it possible to have at least one property required in Mongoose?


You can use custom function as the value of the required property.

const example = new Schema({  name: {    type: String,    required: function() {      return !this.description || !this.countries    },    unique: true  },  description: String,  countries: {    type: [      {        type: String,      }    ],  },  email: {    type: String  },  sex: {    type: String  },});


I doubt that there is a built-in way to achieve this specific type of validation. Here's how you could achieve what you want using the validate method:

const example = new Schema({  name: {    type: String,    unique: true,    validate() {      return this.name || this.countries && this.countries.length > 0 || this.description    }  },  description: {    type: String,    validate() {      return this.name || this.countries && this.countries.length > 0 || this.description    }  },  countries: {    type: [String],    validate() {      return this.name || this.countries && this.countries.length > 0 || this.description    }  }});

It will be called for all three fields in your schema, and as long as at least one of them is not null, they will all be valid. If all three are missing, then all three will be invalid. You can also tune this to fit some more specific needs of yours.

Note that this works because the context (the value of this) of the validate method refers to the model instance.

Edit: better yet, use the required method, which basically works in the same way, as pointed out in the other answer.