Schematype

Mongoose

Schema

Connection

Document

Model

Query

QueryCursor

Aggregate

AggregationCursor

Schematype

Virtualtype

Error

Array

SchemaArray

DocumentArrayPath

SingleNestedPath


SchemaType()

Parameters

SchemaType constructor. Do not instantiate SchemaType directly. Mongoose converts your schema paths into SchemaTypes automatically.

Example:

  1. const schema = new Schema({ name: String });
  2. schema.path('name') instanceof SchemaType; // true

SchemaType.prototype.cast()

Parameters
  • value «Object» value to cast

  • doc «Document» document that triggers the casting

  • init «Boolean»

The function that Mongoose calls to cast arbitrary values to this SchemaType.


SchemaType.prototype.default()

Parameters
  • val «Function|any» the default value
Returns:
  • «defaultValue»

Sets a default value for this SchemaType.

Example:

  1. const schema = new Schema({ n: { type: Number, default: 10 })
  2. const M = db.model('M', schema)
  3. const m = new M;
  4. console.log(m.n) // 10

Defaults can be either functions which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.

Example:

  1. // values are cast:
  2. const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
  3. const M = db.model('M', schema)
  4. const m = new M;
  5. console.log(m.aNumber) // 4.815162342
  6. // default unique objects for Mixed types:
  7. const schema = new Schema({ mixed: Schema.Types.Mixed });
  8. schema.path('mixed').default(function () {
  9. return {};
  10. });
  11. // if we don't use a function to return object literals for Mixed defaults,
  12. // each document will receive a reference to the same object literal creating
  13. // a "shared" object instance:
  14. const schema = new Schema({ mixed: Schema.Types.Mixed });
  15. schema.path('mixed').default({});
  16. const M = db.model('M', schema);
  17. const m1 = new M;
  18. m1.mixed.added = 1;
  19. console.log(m1.mixed); // { added: 1 }
  20. const m2 = new M;
  21. console.log(m2.mixed); // { added: 1 }

SchemaType.prototype.get()

Parameters
  • fn «Function»
Returns:
  • «SchemaType» this

Adds a getter to this schematype.

Example:

  1. function dob (val) {
  2. if (!val) return val;
  3. return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
  4. }
  5. // defining within the schema
  6. const s = new Schema({ born: { type: Date, get: dob })
  7. // or by retreiving its SchemaType
  8. const s = new Schema({ born: Date })
  9. s.path('born').get(dob)

Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.

Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:

  1. function obfuscate (cc) {
  2. return '****-****-****-' + cc.slice(cc.length-4, cc.length);
  3. }
  4. const AccountSchema = new Schema({
  5. creditCardNumber: { type: String, get: obfuscate }
  6. });
  7. const Account = db.model('Account', AccountSchema);
  8. Account.findById(id, function (err, found) {
  9. console.log(found.creditCardNumber); // '****-****-****-1234'
  10. });

Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema.

  1. function inspector (val, schematype) {
  2. if (schematype.options.required) {
  3. return schematype.path + ' is required';
  4. } else {
  5. return schematype.path + ' is not';
  6. }
  7. }
  8. const VirusSchema = new Schema({
  9. name: { type: String, required: true, get: inspector },
  10. taxonomy: { type: String, get: inspector }
  11. })
  12. const Virus = db.model('Virus', VirusSchema);
  13. Virus.findById(id, function (err, virus) {
  14. console.log(virus.name); // name is required
  15. console.log(virus.taxonomy); // taxonomy is not
  16. })

SchemaType.prototype.immutable()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Defines this path as immutable. Mongoose prevents you from changing immutable paths unless the parent document has isNew: true.

Example:

  1. const schema = new Schema({
  2. name: { type: String, immutable: true },
  3. age: Number
  4. });
  5. const Model = mongoose.model('Test', schema);
  6. await Model.create({ name: 'test' });
  7. const doc = await Model.findOne();
  8. doc.isNew; // false
  9. doc.name = 'new name';
  10. doc.name; // 'test', because `name` is immutable

Mongoose also prevents changing immutable properties using updateOne() and updateMany() based on strict mode.

Example:

  1. // Mongoose will strip out the `name` update, because `name` is immutable
  2. Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } });
  3. // If `strict` is set to 'throw', Mongoose will throw an error if you
  4. // update `name`
  5. const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }).
  6. then(() => null, err => err);
  7. err.name; // StrictModeError
  8. // If `strict` is `false`, Mongoose allows updating `name` even though
  9. // the property is immutable.
  10. Model.updateOne({}, { name: 'test2' }, { strict: false });

SchemaType.prototype.index()

Parameters
  • options «Object|Boolean|String»
Returns:
  • «SchemaType» this

Declares the index options for this schematype.

Example:

  1. const s = new Schema({ name: { type: String, index: true })
  2. const s = new Schema({ loc: { type: [Number], index: 'hashed' })
  3. const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
  4. const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
  5. const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
  6. s.path('my.path').index(true);
  7. s.path('my.date').index({ expires: 60 });
  8. s.path('my.path').index({ unique: true, sparse: true });

NOTE:

Indexes are created in the background by default. If background is set to false, MongoDB will not execute any read/write operations you send until the index build. Specify background: false to override Mongoose’s default.


SchemaType.prototype.ref()

Parameters
  • ref «String|Model|Function» either a model name, a Model, or a function that returns a model name or model.
Returns:
  • «SchemaType» this

Set the model that this path refers to. This is the option that populate looks at to determine the foreign collection it should query.

Example:

  1. const userSchema = new Schema({ name: String });
  2. const User = mongoose.model('User', userSchema);
  3. const postSchema = new Schema({ user: mongoose.ObjectId });
  4. postSchema.path('user').ref('User'); // Can set ref to a model name
  5. postSchema.path('user').ref(User); // Or a model class
  6. postSchema.path('user').ref(() => 'User'); // Or a function that returns the model name
  7. postSchema.path('user').ref(() => User); // Or a function that returns the model class
  8. // Or you can just declare the `ref` inline in your schema
  9. const postSchema2 = new Schema({
  10. user: { type: mongoose.ObjectId, ref: User }
  11. });

SchemaType.prototype.required()

Parameters
  • required «Boolean|Function|Object» enable/disable the validator, or function that returns required boolean, or options object

  • [options.isRequired] «Boolean|Function» enable/disable the validator, or function that returns required boolean

  • [options.ErrorConstructor] «Function» custom error constructor. The constructor receives 1 parameter, an object containing the validator properties.

  • [message] «String» optional custom error message

Returns:
  • «SchemaType» this

Adds a required validator to this SchemaType. The validator gets added to the front of this SchemaType’s validators array using unshift().

Example:

  1. const s = new Schema({ born: { type: Date, required: true })
  2. // or with custom error message
  3. const s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
  4. // or with a function
  5. const s = new Schema({
  6. userId: ObjectId,
  7. username: {
  8. type: String,
  9. required: function() { return this.userId != null; }
  10. }
  11. })
  12. // or with a function and a custom message
  13. const s = new Schema({
  14. userId: ObjectId,
  15. username: {
  16. type: String,
  17. required: [
  18. function() { return this.userId != null; },
  19. 'username is required if id is specified'
  20. ]
  21. }
  22. })
  23. // or through the path API
  24. s.path('name').required(true);
  25. // with custom error messaging
  26. s.path('name').required(true, 'grrr :( ');
  27. // or make a path conditionally required based on a function
  28. const isOver18 = function() { return this.age >= 18; };
  29. s.path('voterRegistrationId').required(isOver18);

The required validator uses the SchemaType’s checkRequired function to determine whether a given value satisfies the required validator. By default, a value satisfies the required validator if val != null (that is, if the value is not null nor undefined). However, most built-in mongoose schema types override the default checkRequired function:


SchemaType.prototype.select()

Parameters
  • val «Boolean»
Returns:
  • «SchemaType» this

Sets default select() behavior for this path.

Set to true if this path should always be included in the results, false if it should be excluded by default. This setting can be overridden at the query level.

Example:

  1. T = db.model('T', new Schema({ x: { type: String, select: true }}));
  2. T.find(..); // field x will always be selected ..
  3. // .. unless overridden;
  4. T.find().select('-x').exec(callback);

SchemaType.prototype.set()

Parameters
  • fn «Function»
Returns:
  • «SchemaType» this

Adds a setter to this schematype.

Example:

  1. function capitalize (val) {
  2. if (typeof val !== 'string') val = '';
  3. return val.charAt(0).toUpperCase() + val.substring(1);
  4. }
  5. // defining within the schema
  6. const s = new Schema({ name: { type: String, set: capitalize }});
  7. // or with the SchemaType
  8. const s = new Schema({ name: String })
  9. s.path('name').set(capitalize);

Setters allow you to transform the data before it gets to the raw mongodb document or query.

Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account — e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM.

You can set up email lower case normalization easily via a Mongoose setter.

  1. function toLower(v) {
  2. return v.toLowerCase();
  3. }
  4. const UserSchema = new Schema({
  5. email: { type: String, set: toLower }
  6. });
  7. const User = db.model('User', UserSchema);
  8. const user = new User({email: 'AVENUE@Q.COM'});
  9. console.log(user.email); // 'avenue@q.com'
  10. // or
  11. const user = new User();
  12. user.email = 'Avenue@Q.com';
  13. console.log(user.email); // 'avenue@q.com'
  14. User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com'

As you can see above, setters allow you to transform the data before it stored in MongoDB, or before executing a query.

NOTE: we could have also just used the built-in lowercase: true SchemaType option instead of defining our own function.

  1. new Schema({ email: { type: String, lowercase: true }})

Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema.

  1. function inspector (val, schematype) {
  2. if (schematype.options.required) {
  3. return schematype.path + ' is required';
  4. } else {
  5. return val;
  6. }
  7. }
  8. const VirusSchema = new Schema({
  9. name: { type: String, required: true, set: inspector },
  10. taxonomy: { type: String, set: inspector }
  11. })
  12. const Virus = db.model('Virus', VirusSchema);
  13. const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });
  14. console.log(v.name); // name is required
  15. console.log(v.taxonomy); // Parvovirinae

You can also use setters to modify other properties on the document. If you’re setting a property name on a document, the setter will run with this as the document. Be careful, in mongoose 5 setters will also run when querying by name with this as the query.

  1. const nameSchema = new Schema({ name: String, keywords: [String] });
  2. nameSchema.path('name').set(function(v) {
  3. // Need to check if `this` is a document, because in mongoose 5
  4. // setters will also run on queries, in which case `this` will be a
  5. // mongoose query object.
  6. if (this instanceof Document && v != null) {
  7. this.keywords = v.split(' ');
  8. }
  9. return v;
  10. });

SchemaType.prototype.sparse()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Declares a sparse index.

Example:

  1. const s = new Schema({ name: { type: String, sparse: true } });
  2. s.path('name').index({ sparse: true });

SchemaType.prototype.text()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Declares a full text index.

Example:

  1. const s = new Schema({name : {type: String, text : true })
  2. s.path('name').index({text : true});

SchemaType.prototype.transform()

Parameters
  • fn «Function»
Returns:
  • «SchemaType» this

Defines a custom function for transforming this path when converting a document to JSON.

Mongoose calls this function with one parameter: the current value of the path. Mongoose then uses the return value in the JSON output.

Example:

  1. const schema = new Schema({
  2. date: { type: Date, transform: v => v.getFullYear() }
  3. });
  4. const Model = mongoose.model('Test', schema);
  5. await Model.create({ date: new Date('2016-06-01') });
  6. const doc = await Model.findOne();
  7. doc.date instanceof Date; // true
  8. doc.toJSON().date; // 2016 as a number
  9. JSON.stringify(doc); // '{"_id":...,"date":2016}'

SchemaType.prototype.unique()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Declares an unique index.

Example:

  1. const s = new Schema({ name: { type: String, unique: true }});
  2. s.path('name').index({ unique: true });

NOTE: violating the constraint returns an E11000 error from MongoDB when saving, not a Mongoose validation error.


SchemaType.prototype.validate()

Parameters
  • obj «RegExp|Function|Object» validator function, or hash describing options

  • [obj.validator] «Function» validator function. If the validator function returns undefined or a truthy value, validation succeeds. If it returns falsy (except undefined) or throws an error, validation fails.

  • [obj.message] «String|Function» optional error message. If function, should return the error message as a string

  • [obj.propsParameter=false] «Boolean» If true, Mongoose will pass the validator properties object (with the validator function, message, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators rely on positional args, so turning this on may cause unpredictable behavior in external validators.

  • [errorMsg] «String|Function» optional error message. If function, should return the error message as a string

  • [type] «String» optional validator type

Returns:
  • «SchemaType» this

Adds validator(s) for this document path.

Validators always receive the value to validate as their first argument and must return Boolean. Returning false or throwing an error means validation failed.

The error message argument is optional. If not passed, the default generic error message template will be used.

Examples:

  1. // make sure every value is equal to "something"
  2. function validator (val) {
  3. return val == 'something';
  4. }
  5. new Schema({ name: { type: String, validate: validator }});
  6. // with a custom error message
  7. const custom = [validator, 'Uh oh, {PATH} does not equal "something".']
  8. new Schema({ name: { type: String, validate: custom }});
  9. // adding many validators at a time
  10. const many = [
  11. { validator: validator, msg: 'uh oh' }
  12. , { validator: anotherValidator, msg: 'failed' }
  13. ]
  14. new Schema({ name: { type: String, validate: many }});
  15. // or utilizing SchemaType methods directly:
  16. const schema = new Schema({ name: 'string' });
  17. schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');

Error message templates:

From the examples above, you may have noticed that error messages support basic templating. There are a few other template keywords besides {PATH} and {VALUE} too. To find out more, details are available here.

If Mongoose’s built-in error message templating isn’t enough, Mongoose supports setting the message property to a function.

  1. schema.path('name').validate({
  2. validator: function() { return v.length > 5; },
  3. // `errors['name']` will be "name must have length 5, got 'foo'"
  4. message: function(props) {
  5. return `${props.path} must have length 5, got '${props.value}'`;
  6. }
  7. });

To bypass Mongoose’s error messages and just copy the error message that the validator throws, do this:

  1. schema.path('name').validate({
  2. validator: function() { throw new Error('Oops!'); },
  3. // `errors['name']` will be "Oops!"
  4. message: function(props) { return props.reason.message; }
  5. });

Asynchronous validation:

Mongoose supports validators that return a promise. A validator that returns a promise is called an async validator. Async validators run in parallel, and validate() will wait until all async validators have settled.

  1. schema.path('name').validate({
  2. validator: function (value) {
  3. return new Promise(function (resolve, reject) {
  4. resolve(false); // validation failed
  5. });
  6. }
  7. });

You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.

Validation occurs pre('save') or whenever you manually execute document#validate.

If validation fails during pre('save') and no callback was passed to receive the error, an error event will be emitted on your Models associated db connection, passing the validation error object along.

  1. const conn = mongoose.createConnection(..);
  2. conn.on('error', handleError);
  3. const Product = conn.model('Product', yourSchema);
  4. const dvd = new Product(..);
  5. dvd.save(); // emits error on the `conn` above

If you want to handle these errors at the Model level, add an error listener to your Model as shown below.

  1. // registering an error listener on the Model lets us handle errors more locally
  2. Product.on('error', handleError);

Schematype.cast()

Parameters
  • caster «Function|false» Function that casts arbitrary values to this type, or throws an error if casting failed
Returns:
  • «Function»

Get/set the function used to cast arbitrary values to this type.

Example:

  1. // Disallow `null` for numbers, and don't try to cast any values to
  2. // numbers, so even strings like '123' will cause a CastError.
  3. mongoose.Number.cast(function(v) {
  4. assert.ok(v === undefined || typeof v === 'number');
  5. return v;
  6. });

Schematype.cast()

Parameters
  • caster «Function|false» Function that casts arbitrary values to this type, or throws an error if casting failed
Returns:
  • «Function»

Get/set the function used to cast arbitrary values to this particular schematype instance. Overrides SchemaType.cast().

Example:

  1. // Disallow `null` for numbers, and don't try to cast any values to
  2. // numbers, so even strings like '123' will cause a CastError.
  3. const number = new mongoose.Number('mypath', {});
  4. number.cast(function(v) {
  5. assert.ok(v === undefined || typeof v === 'number');
  6. return v;
  7. });

Schematype.checkRequired()

Parameters
  • fn «Function»
Returns:
  • «Function»

Override the function the required validator uses to check whether a value passes the required check. Override this on the individual SchemaType.

Example:

  1. // Use this to allow empty strings to pass the `required` validator
  2. mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');

Schematype.get()

Parameters
  • getter «Function»
Returns:
  • «this»

Attaches a getter for all instances of this schema type.

Example:

  1. // Make all numbers round down
  2. mongoose.Number.get(function(v) { return Math.floor(v); });

Schematype.set()

Parameters
  • option «String» The name of the option you’d like to set (e.g. trim, lowercase, etc…)

  • value «*» The value of the option you’d like to set.

Returns:
  • «void»

Sets a default option for this schema type.

Example:

  1. // Make all strings be trimmed by default
  2. mongoose.SchemaTypes.String.set('trim', true);