Schema

Schema()

Parameters
  • [definition] «Object|Schema|Array» Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas

  • [options] «Object»

Inherits:

Schema constructor.

Example:

  1. const child = new Schema({ name: String });
  2. const schema = new Schema({ name: String, age: Number, children: [child] });
  3. const Tree = mongoose.model('Tree', schema);
  4. // setting schema options
  5. new Schema({ name: String }, { _id: false, autoIndex: false })

Options:

Options for Nested Schemas:

  • excludeIndexes: bool - defaults to false. If true, skip building indexes on this schema’s paths.

Note:

When nesting schemas, (children in the example above), always declare the child schema first before passing it into its parent.


Schema.Types

Type:
  • «property»

The various built-in Mongoose Schema Types.

Example:

  1. const mongoose = require('mongoose');
  2. const ObjectId = mongoose.Schema.Types.ObjectId;

Types:

Using this exposed access to the Mixed SchemaType, we can use them in our schema.

  1. const Mixed = mongoose.Schema.Types.Mixed;
  2. new mongoose.Schema({ _user: Mixed })

Schema.indexTypes

Type:
  • «property»

The allowed index types


Schema.prototype.add()

Parameters
  • obj «Object|Schema» plain object with paths to add, or another schema

  • [prefix] «String» path to prefix the newly added paths with

Returns:
  • «Schema» the Schema instance

Adds key path / schema type pairs to this schema.

Example:

  1. const ToySchema = new Schema();
  2. ToySchema.add({ name: 'string', color: 'string', price: 'number' });
  3. const TurboManSchema = new Schema();
  4. // You can also `add()` another schema and copy over all paths, virtuals,
  5. // getters, setters, indexes, methods, and statics.
  6. TurboManSchema.add(ToySchema).add({ year: Number });

Schema.prototype.childSchemas

Type:
  • «property»

Array of child schemas (from document arrays and single nested subdocs) and their corresponding compiled models. Each element of the array is an object with 2 properties: schema and model.

This property is typically only useful for plugin authors and advanced users. You do not need to interact with this property at all to use mongoose.


Schema.prototype.clone()

Returns:
  • «Schema» the cloned schema

Returns a deep copy of the schema

Example:

  1. const schema = new Schema({ name: String });
  2. const clone = schema.clone();
  3. clone === schema; // false
  4. clone.path('name'); // SchemaString { ... }

Schema.prototype.eachPath()

Parameters
  • fn «Function» callback function
Returns:
  • «Schema» this

Iterates the schemas paths similar to Array#forEach.

The callback is passed the pathname and the schemaType instance.

Example:

  1. const userSchema = new Schema({ name: String, registeredAt: Date });
  2. userSchema.eachPath((pathname, schematype) => {
  3. // Prints twice:
  4. // name SchemaString { ... }
  5. // registeredAt SchemaDate { ... }
  6. console.log(pathname, schematype);
  7. });

Schema.prototype.get()

Parameters
  • key «String» option name
Returns:
  • «Any» the option’s value

Gets a schema option.

Example:

  1. schema.get('strict'); // true
  2. schema.set('strict', false);
  3. schema.get('strict'); // false

Schema.prototype.index()

Parameters
  • fields «Object»
  • [options] «Object» Options to pass to MongoDB driver’s createIndex() function

  • | «String» number} [options.expires=null] Mongoose-specific syntactic sugar, uses ms to convert expires option into seconds for the expireAfterSeconds in the above link.

Defines an index (most likely compound) for this schema.

Example

  1. schema.index({ first: 1, last: -1 })

Schema.prototype.indexes()

Returns:
  • «Array» list of indexes defined in the schema

Returns a list of indexes that this schema declares, via schema.index() or by index: true in a path’s options. Indexes are expressed as an array [spec, options].

Example:

  1. const userSchema = new Schema({
  2. email: { type: String, required: true, unique: true },
  3. registeredAt: { type: Date, index: true }
  4. });
  5. // [ [ { email: 1 }, { unique: true, background: true } ],
  6. // [ { registeredAt: 1 }, { background: true } ] ]
  7. userSchema.indexes();

Plugins can use the return value of this function to modify a schema’s indexes. For example, the below plugin makes every index unique by default.

  1. function myPlugin(schema) {
  2. for (const index of schema.indexes()) {
  3. if (index[1].unique === undefined) {
  4. index[1].unique = true;
  5. }
  6. }
  7. }

Schema.prototype.loadClass()

Parameters
  • model «Function»
  • [virtualsOnly] «Boolean» if truthy, only pulls virtuals from the class, not methods or statics

Loads an ES6 class into a schema. Maps setters + getters, static methods, and instance methods to schema virtuals, statics, and methods.

Example:

  1. const md5 = require('md5');
  2. const userSchema = new Schema({ email: String });
  3. class UserClass {
  4. // `gravatarImage` becomes a virtual
  5. get gravatarImage() {
  6. const hash = md5(this.email.toLowerCase());
  7. return `https://www.gravatar.com/avatar/${hash}`;
  8. }
  9. // `getProfileUrl()` becomes a document method
  10. getProfileUrl() {
  11. return `https://mysite.com/${this.email}`;
  12. }
  13. // `findByEmail()` becomes a static
  14. static findByEmail(email) {
  15. return this.findOne({ email });
  16. }
  17. }
  18. // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
  19. // and a `findByEmail()` static
  20. userSchema.loadClass(UserClass);

Schema.prototype.method()

Parameters
  • method «String|Object» name

  • [fn] «Function»

Adds an instance method to documents constructed from Models compiled from this schema.

Example

  1. const schema = kittySchema = new Schema(..);
  2. schema.method('meow', function () {
  3. console.log('meeeeeoooooooooooow');
  4. })
  5. const Kitty = mongoose.model('Kitty', schema);
  6. const fizz = new Kitty;
  7. fizz.meow(); // meeeeeooooooooooooow

If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.

  1. schema.method({
  2. purr: function () {}
  3. , scratch: function () {}
  4. });
  5. // later
  6. fizz.purr();
  7. fizz.scratch();

NOTE: Schema.method() adds instance methods to the Schema.methods object. You can also add instance methods directly to the Schema.methods object as seen in the guide


Schema.prototype.obj

Type:
  • «property»

The original object passed to the schema constructor

Example:

  1. const schema = new Schema({ a: String }).add({ b: String });
  2. schema.obj; // { a: String }

Schema.prototype.path()

Parameters
  • path «String»
  • constructor «Object»

Gets/sets schema paths.

Sets a path (if arity 2) Gets a path (if arity 1)

Example

  1. schema.path('name') // returns a SchemaType
  2. schema.path('name', Number) // changes the schemaType of `name` to Number

Schema.prototype.pathType()

Parameters
  • path «String»
Returns:
  • «String»

Returns the pathType of path for this schema.

Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.

Example:

  1. const s = new Schema({ name: String, nested: { foo: String } });
  2. s.virtual('foo').get(() => 42);
  3. s.pathType('name'); // "real"
  4. s.pathType('nested'); // "nested"
  5. s.pathType('foo'); // "virtual"
  6. s.pathType('fail'); // "adhocOrUndefined"

Schema.prototype.paths

Type:
  • «property»

The paths defined on this schema. The keys are the top-level paths in this schema, and the values are instances of the SchemaType class.

Example:

  1. const schema = new Schema({ name: String }, { _id: false });
  2. schema.paths; // { name: SchemaString { ... } }
  3. schema.add({ age: Number });
  4. schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }

Schema.prototype.pick()

Parameters
  • paths «Array» list of paths to pick

  • [options] «Object» options to pass to the schema constructor. Defaults to this.options if not set.

Returns:
  • «Schema»

Returns a new schema that has the picked paths from this schema.

This method is analagous to Lodash’s pick() function for Mongoose schemas.

Example:

  1. const schema = Schema({ name: String, age: Number });
  2. // Creates a new schema with the same `name` path as `schema`,
  3. // but no `age` path.
  4. const newSchema = schema.pick(['name']);
  5. newSchema.path('name'); // SchemaString { ... }
  6. newSchema.path('age'); // undefined

Schema.prototype.plugin()

Parameters
  • plugin «Function» callback

  • [opts] «Object»

Registers a plugin for this schema.

Example:

  1. const s = new Schema({ name: String });
  2. s.plugin(schema => console.log(schema.path('name').path));
  3. mongoose.model('Test', s); // Prints 'name'

Schema.prototype.post()

Parameters
  • The «String|RegExp» method name or regular expression to match method name

  • [options] «Object»

  • [options.document] «Boolean» If name is a hook for both document and query middleware, set to true to run on document middleware.

  • [options.query] «Boolean» If name is a hook for both document and query middleware, set to true to run on query middleware.

  • fn «Function» callback

Defines a post hook for the document

  1. const schema = new Schema(..);
  2. schema.post('save', function (doc) {
  3. console.log('this fired after a document was saved');
  4. });
  5. schema.post('find', function(docs) {
  6. console.log('this fired after you ran a find query');
  7. });
  8. schema.post(/Many$/, function(res) {
  9. console.log('this fired after you ran `updateMany()` or `deleteMany()`);
  10. });
  11. const Model = mongoose.model('Model', schema);
  12. const m = new Model(..);
  13. m.save(function(err) {
  14. console.log('this fires after the `post` hook');
  15. });
  16. m.find(function(err, docs) {
  17. console.log('this fires after the post find hook');
  18. });

Schema.prototype.pre()

Parameters
  • The «String|RegExp» method name or regular expression to match method name

  • [options] «Object»

  • [options.document] «Boolean» If name is a hook for both document and query middleware, set to true to run on document middleware. For example, set options.document to true to apply this hook to Document#deleteOne() rather than Query#deleteOne().

  • [options.query] «Boolean» If name is a hook for both document and query middleware, set to true to run on query middleware.

  • callback «Function»

Defines a pre hook for the model.

Example

  1. const toySchema = new Schema({ name: String, created: Date });
  2. toySchema.pre('save', function(next) {
  3. if (!this.created) this.created = new Date;
  4. next();
  5. });
  6. toySchema.pre('validate', function(next) {
  7. if (this.name !== 'Woody') this.name = 'Woody';
  8. next();
  9. });
  10. // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
  11. toySchema.pre(/^find/, function(next) {
  12. console.log(this.getFilter());
  13. });
  14. // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
  15. toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
  16. console.log(this.getFilter());
  17. });
  18. toySchema.pre('deleteOne', function() {
  19. // Runs when you call `Toy.deleteOne()`
  20. });
  21. toySchema.pre('deleteOne', { document: true }, function() {
  22. // Runs when you call `doc.deleteOne()`
  23. });

Schema.prototype.queue()

Parameters
  • name «String» name of the document method to call later

  • args «Array» arguments to pass to the method

Adds a method call to the queue.

Example:

  1. schema.methods.print = function() { console.log(this); };
  2. schema.queue('print', []); // Print the doc every one is instantiated
  3. const Model = mongoose.model('Test', schema);
  4. new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'

Schema.prototype.remove()

Parameters
  • path «String|Array»
Returns:
  • «Schema» the Schema instance

Removes the given path (or [paths]).

Example:

  1. const schema = new Schema({ name: String, age: Number });
  2. schema.remove('name');
  3. schema.path('name'); // Undefined
  4. schema.path('age'); // SchemaNumber { ... }

Schema.prototype.requiredPaths()

Parameters
  • invalidate «Boolean» refresh the cache
Returns:
  • «Array»

Returns an Array of path strings that are required by this schema.

Example:

  1. const s = new Schema({
  2. name: { type: String, required: true },
  3. age: { type: String, required: true },
  4. notes: String
  5. });
  6. s.requiredPaths(); // [ 'age', 'name' ]

Schema.prototype.set()

Parameters
  • key «String» option name

  • [value] «Object» if not passed, the current option value is returned

Sets a schema option.

Example

  1. schema.set('strict'); // 'true' by default
  2. schema.set('strict', false); // Sets 'strict' to false
  3. schema.set('strict'); // 'false'

Schema.prototype.static()

Parameters
  • name «String|Object»
  • [fn] «Function»

Adds static “class” methods to Models compiled from this schema.

Example

  1. const schema = new Schema(..);
  2. // Equivalent to `schema.statics.findByName = function(name) {}`;
  3. schema.static('findByName', function(name) {
  4. return this.find({ name: name });
  5. });
  6. const Drink = mongoose.model('Drink', schema);
  7. await Drink.findByName('LaCroix');

If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.


Schema.prototype.virtual()

Parameters
  • name «String»
  • [options] «Object»

  • [options.ref] «String|Model» model name or model instance. Marks this as a populate virtual.

  • [options.localField] «String|Function» Required for populate virtuals. See populate virtual docs for more information.

  • [options.foreignField] «String|Function» Required for populate virtuals. See populate virtual docs for more information.

  • [options.justOne=false] «Boolean|Function» Only works with populate virtuals. If truthy, will be a single doc or null. Otherwise, the populate virtual will be an array.

  • [options.count=false] «Boolean» Only works with populate virtuals. If truthy, this populate virtual will contain the number of documents rather than the documents themselves when you populate().

  • [options.get=null] «Function|null» Adds a getter to this virtual to transform the populated doc.

Returns:
  • «VirtualType»

Creates a virtual type with the given name.


Schema.prototype.virtualpath()

Parameters
  • name «String»
Returns:
  • «VirtualType»

Returns the virtual type with the given name.


Schema.prototype.virtuals

Type:
  • «property»

Object containing all virtuals defined on this schema. The objects’ keys are the virtual paths and values are instances of VirtualType.

This property is typically only useful for plugin authors and advanced users. You do not need to interact with this property at all to use mongoose.

Example:

  1. const schema = new Schema({});
  2. schema.virtual('answer').get(() => 42);
  3. console.log(schema.virtuals); // { answer: VirtualType { path: 'answer', ... } }
  4. console.log(schema.virtuals['answer'].getters[0].call()); // 42

Schema.reserved

Type:
  • «property»

Reserved document keys.

Keys in this object are names that are warned in schema declarations because they have the potential to break Mongoose/ Mongoose plugins functionality. If you create a schema using new Schema() with one of these property names, Mongoose will log a warning.

  • _posts
  • _pres
  • collection
  • emit
  • errors
  • get
  • init
  • isModified
  • isNew
  • listeners
  • modelName
  • on
  • once
  • populated
  • prototype
  • remove
  • removeListener
  • save
  • schema
  • toObject
  • validate

NOTE: Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on.

  1. const schema = new Schema(..);
  2. schema.methods.init = function () {} // potentially breaking