SchemaTypeOptions


SchemaTypeOptions()

The options defined on a schematype.

Example:

const schema = new Schema({ name: String });
schema.path('name').options instanceof mongoose.SchemaTypeOptions; // true

SchemaTypeOptions.prototype.cast

Type:
  • «String»

Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose's default cast error message.

Example:

const schema = new Schema({
  num: {
    type: Number,
    cast: '{VALUE} is not a valid number'
  }
});

// Throws 'CastError: "bad" is not a valid number'
schema.path('num').cast('bad');

const Model = mongoose.model('Test', schema);
const doc = new Model({ num: 'fail' });
const err = doc.validateSync();

err.errors['num']; // 'CastError: "fail" is not a valid number'

SchemaTypeOptions.prototype.default

Type:
  • «Function|Any»

The default value for this path. If a function, Mongoose executes the function and uses the return value as the default.


SchemaTypeOptions.prototype.immutable

Type:
  • «Function|Boolean»

If truthy, Mongoose will disallow changes to this path once the document is saved to the database for the first time. Read more about immutability in Mongoose here.


SchemaTypeOptions.prototype.index

Type:
  • «Boolean|Number|Object»

If truthy, Mongoose will build an index on this path when the model is compiled.


SchemaTypeOptions.prototype.ref

Type:
  • «Function|String»

The model that populate() should use if populating this path.


SchemaTypeOptions.prototype.required

Type:
  • «Function|Boolean»

If true, attach a required validator to this path, which ensures this path path cannot be set to a nullish value. If a function, Mongoose calls the function and only checks for nullish values if the function returns a truthy value.


SchemaTypeOptions.prototype.select

Type:
  • «Boolean|Number»

Whether to include or exclude this path by default when loading documents using find(), findOne(), etc.


SchemaTypeOptions.prototype.sparse

Type:
  • «Boolean|Number»

If truthy, Mongoose will build a sparse index on this path.


SchemaTypeOptions.prototype.text

Type:
  • «Boolean|Number|Object»

If truthy, Mongoose will build a text index on this path.


SchemaTypeOptions.prototype.type

Type:
  • «Function|String|Object»

The type to cast this path to.


SchemaTypeOptions.prototype.unique

Type:
  • «Boolean|Number»

If truthy, Mongoose will build a unique index on this path when the model is compiled. The unique option is not a validator.


SchemaTypeOptions.prototype.validate

Type:
  • «Function|Object»

Function or object describing how to validate this schematype.