Mongoose schema optional fields Mongoose schema optional fields mongoose mongoose

Mongoose schema optional fields


All fields in a mongoose schema are optional by default (besides _id, of course).

A field is only required if you add required: true to its definition.

So define your schema as the superset of all possible fields, adding required: true to the fields that are required.


In addition to optional (default) and required, a field can also be conditionally required, based on one or more of the other fields.

For example, require password only if email exists:

var userschema = mongoose.Schema({    org: String,    username: String,    fullname: String,    password: {        type: String,        required: function(){            return this.email? true : false         }    },    email: String});