Schemas

If you haven’t yet done so, please take a minute to read the quickstart to get an idea of how Mongoose works. If you are migrating from 4.x to 5.x please take a moment to read the migration guide.

Defining your schema

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

  1. import mongoose from 'mongoose';
  2. const { Schema } = mongoose;
  3. const blogSchema = new Schema({
  4. title: String, // String is shorthand for {type: String}
  5. author: String,
  6. body: String,
  7. comments: [{ body: String, date: Date }],
  8. date: { type: Date, default: Date.now },
  9. hidden: Boolean,
  10. meta: {
  11. votes: Number,
  12. favs: Number
  13. }
  14. });

If you want to add additional keys later, use the Schema#add method.

Each key in our code blogSchema defines a property in our documents which will be cast to its associated SchemaType. For example, we’ve defined a property title which will be cast to the String SchemaType and property date which will be cast to a Date SchemaType.

Notice above that if a property only requires a type, it can be specified using a shorthand notation (contrast the title property above with the date property).

Keys may also be assigned nested objects containing further key/type definitions like the meta property above. This will happen whenever a key’s value is a POJO that doesn’t have a type property.

In these cases, Mongoose only creates actual schema paths for leaves in the tree. (like meta.votes and meta.favs above), and the branches do not have actual paths. A side-effect of this is that meta above cannot have its own validation. If validation is needed up the tree, a path needs to be created up the tree - see the Subdocuments section for more information on how to do this. Also read the Mixed subsection of the SchemaTypes guide for some gotchas.

The permitted SchemaTypes are:

Read more about SchemaTypes here.

Schemas not only define the structure of your document and casting of properties, they also define document instance methods, static Model methods, compound indexes, and document lifecycle hooks called middleware.

Creating a model

To use our schema definition, we need to convert our blogSchema into a Model we can work with. To do so, we pass it into mongoose.model(modelName, schema):

  1. const Blog = mongoose.model('Blog', blogSchema);
  2. // ready to go!

Ids

By default, Mongoose adds an _id property to your schemas.

  1. const schema = new Schema();
  2. schema.path('_id'); // ObjectId { ... }

When you create a new document with the automatically added _id property, Mongoose creates a new _id of type ObjectId to your document.

  1. const Model = mongoose.model('Test', schema);
  2. const doc = new Model();
  3. doc._id instanceof mongoose.Types.ObjectId; // true

You can also overwrite Mongoose’s default _id with your own _id. Just be careful: Mongoose will refuse to save a document that doesn’t have an _id, so you’re responsible for setting _id if you define your own _id path.

  1. const schema = new Schema({ _id: Number });
  2. const Model = mongoose.model('Test', schema);
  3. const doc = new Model();
  4. await doc.save(); // Throws "document must have an _id before saving"
  5. doc._id = 1;
  6. await doc.save(); // works

Instance methods

Instances of Models are documents. Documents have many of their own built-in instance methods. We may also define our own custom document instance methods.

  1. // define a schema
  2. const animalSchema = new Schema({ name: String, type: String });
  3. // assign a function to the "methods" object of our animalSchema
  4. animalSchema.methods.findSimilarTypes = function(cb) {
  5. return mongoose.model('Animal').find({ type: this.type }, cb);
  6. };

Now all of our animal instances have a findSimilarTypes method available to them.

  1. const Animal = mongoose.model('Animal', animalSchema);
  2. const dog = new Animal({ type: 'dog' });
  3. dog.findSimilarTypes((err, dogs) => {
  4. console.log(dogs); // woof
  5. });
  • Overwriting a default mongoose document method may lead to unpredictable results. See this for more details.
  • The example above uses the Schema.methods object directly to save an instance method. You can also use the Schema.method() helper as described here.
  • Do not declare methods using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so your method will not have access to the document and the above examples will not work.

Statics

You can also add static functions to your model. There are two equivalent ways to add a static:

  1. // Assign a function to the "statics" object of our animalSchema
  2. animalSchema.statics.findByName = function(name) {
  3. return this.find({ name: new RegExp(name, 'i') });
  4. };
  5. // Or, equivalently, you can call `animalSchema.static()`.
  6. animalSchema.static('findByBreed', function(breed) { return this.find({ breed }); });
  7. const Animal = mongoose.model('Animal', animalSchema);
  8. let animals = await Animal.findByName('fido');
  9. animals = animals.concat(await Animal.findByBreed('Poodle'));

Do not declare statics using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so the above examples will not work because of the value of this.

Query Helpers

You can also add query helper functions, which are like instance methods but for mongoose queries. Query helper methods let you extend mongoose’s chainable query builder API.

  1. animalSchema.query.byName = function(name) {
  2. return this.where({ name: new RegExp(name, 'i') })
  3. };
  4. const Animal = mongoose.model('Animal', animalSchema);
  5. Animal.find().byName('fido').exec((err, animals) => {
  6. console.log(animals);
  7. });
  8. Animal.findOne().byName('fido').exec((err, animal) => {
  9. console.log(animal);
  10. });

Indexes

MongoDB supports secondary indexes. With mongoose, we define these indexes within our Schema at the path level or the schema level. Defining indexes at the schema level is necessary when creating compound indexes.

  1. const animalSchema = new Schema({
  2. name: String,
  3. type: String,
  4. tags: { type: [String], index: true } // field level
  5. });
  6. animalSchema.index({ name: 1, type: -1 }); // schema level

When your application starts up, Mongoose automatically calls createIndex for each defined index in your schema. Mongoose will call createIndex for each index sequentially, and emit an ‘index’ event on the model when all the createIndex calls succeeded or when there was an error. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting the autoIndex option of your schema to false, or globally on the connection by setting the option autoIndex to false.

  1. mongoose.connect('mongodb://user:pass@localhost:port/database', { autoIndex: false });
  2. // or
  3. mongoose.createConnection('mongodb://user:pass@localhost:port/database', { autoIndex: false });
  4. // or
  5. animalSchema.set('autoIndex', false);
  6. // or
  7. new Schema({..}, { autoIndex: false });

Mongoose will emit an index event on the model when indexes are done building or an error occurred.

  1. // Will cause an error because mongodb has an _id index by default that
  2. // is not sparse
  3. animalSchema.index({ _id: 1 }, { sparse: true });
  4. const Animal = mongoose.model('Animal', animalSchema);
  5. Animal.on('index', error => {
  6. // "_id index cannot be sparse"
  7. console.log(error.message);
  8. });

See also the Model#ensureIndexes method.

Virtuals

Virtuals are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters are useful for de-composing a single value into multiple values for storage.

  1. // define a schema
  2. const personSchema = new Schema({
  3. name: {
  4. first: String,
  5. last: String
  6. }
  7. });
  8. // compile our model
  9. const Person = mongoose.model('Person', personSchema);
  10. // create a document
  11. const axl = new Person({
  12. name: { first: 'Axl', last: 'Rose' }
  13. });

Suppose you want to print out the person’s full name. You could do it yourself:

  1. console.log(axl.name.first + ' ' + axl.name.last); // Axl Rose

But concatenating the first and last name every time can get cumbersome. And what if you want to do some extra processing on the name, like removing diacritics? A virtual property getter lets you define a fullName property that won’t get persisted to MongoDB.

  1. personSchema.virtual('fullName').get(function() {
  2. return this.name.first + ' ' + this.name.last;
  3. });

Now, mongoose will call your getter function every time you access the fullName property:

  1. console.log(axl.fullName); // Axl Rose

If you use toJSON() or toObject() mongoose will not include virtuals by default. This includes the output of calling JSON.stringify() on a Mongoose document, because JSON.stringify() calls toJSON(). Pass { virtuals: true } to either toObject() or toJSON().

You can also add a custom setter to your virtual that will let you set both first name and last name via the fullName virtual.

  1. personSchema.virtual('fullName').
  2. get(function() {
  3. return this.name.first + ' ' + this.name.last;
  4. }).
  5. set(function(v) {
  6. this.name.first = v.substr(0, v.indexOf(' '));
  7. this.name.last = v.substr(v.indexOf(' ') + 1);
  8. });
  9. axl.fullName = 'William Rose'; // Now `axl.name.first` is "William"

Virtual property setters are applied before other validation. So the example above would still work even if the first and last name fields were required.

Only non-virtual properties work as part of queries and for field selection. Since virtuals are not stored in MongoDB, you can’t query with them.

You can learn more about virtuals here.

Aliases

Aliases are a particular type of virtual where the getter and setter seamlessly get and set another property. This is handy for saving network bandwidth, so you can convert a short property name stored in the database into a longer name for code readability.

  1. const personSchema = new Schema({
  2. n: {
  3. type: String,
  4. // Now accessing `name` will get you the value of `n`, and setting `name` will set the value of `n`
  5. alias: 'name'
  6. }
  7. });
  8. // Setting `name` will propagate to `n`
  9. const person = new Person({ name: 'Val' });
  10. console.log(person); // { n: 'Val' }
  11. console.log(person.toObject({ virtuals: true })); // { n: 'Val', name: 'Val' }
  12. console.log(person.name); // "Val"
  13. person.name = 'Not Val';
  14. console.log(person); // { n: 'Not Val' }

You can also declare aliases on nested paths. It is easier to use nested schemas and subdocuments, but you can also declare nested path aliases inline as long as you use the full nested path nested.myProp as the alias.

  1. const childSchema = new Schema({
  2. n: {
  3. type: String,
  4. alias: 'name'
  5. }
  6. }, { _id: false });
  7. const parentSchema = new Schema({
  8. // If in a child schema, alias doesn't need to include the full nested path
  9. c: childSchema,
  10. name: {
  11. f: {
  12. type: String,
  13. // Alias needs to include the full nested path if declared inline
  14. alias: 'name.first'
  15. }
  16. }
  17. });

Options

Schemas have a few configurable options which can be passed to the constructor or to the set method:

  1. new Schema({..}, options);
  2. // or
  3. const schema = new Schema({..});
  4. schema.set(option, value);

Valid options:

option: autoIndex

By default, Mongoose’s init() function creates all the indexes defined in your model’s schema by calling Model.createIndexes() after you successfully connect to MongoDB. Creating indexes automatically is great for development and test environments. But index builds can also create significant load on your production database. If you want to manage indexes carefully in production, you can set autoIndex to false.

  1. const schema = new Schema({..}, { autoIndex: false });
  2. const Clock = mongoose.model('Clock', schema);
  3. Clock.ensureIndexes(callback);

The autoIndex option is set to true by default. You can change this default by setting mongoose.set('autoIndex', false);

option: autoCreate

Before Mongoose builds indexes, it calls Model.createCollection() to create the underlying collection in MongoDB if autoCreate is set to true. Calling createCollection() sets the collection’s default collation based on the collation option and establishes the collection as a capped collection if you set the capped schema option. Like autoIndex, setting autoCreate to true is helpful for development and test environments.

Unfortunately, createCollection() cannot change an existing collection. For example, if you add capped: 1024 to your schema and the existing collection is not capped, createCollection() will throw an error. Generally, autoCreate should be false for production environments.

  1. const schema = new Schema({..}, { autoCreate: true, capped: 1024 });
  2. const Clock = mongoose.model('Clock', schema);
  3. // Mongoose will create the capped collection for you.

Unlike autoIndex, autoCreate is false by default. You can change this default by setting mongoose.set('autoCreate', true);

option: bufferCommands

By default, mongoose buffers commands when the connection goes down until the driver manages to reconnect. To disable buffering, set bufferCommands to false.

  1. const schema = new Schema({..}, { bufferCommands: false });

The schema bufferCommands option overrides the global bufferCommands option.

  1. mongoose.set('bufferCommands', true);
  2. // Schema option below overrides the above, if the schema option is set.
  3. const schema = new Schema({..}, { bufferCommands: false });

option: bufferTimeoutMS

If bufferCommands is on, this option sets the maximum amount of time Mongoose buffering will wait before throwing an error. If not specified, Mongoose will use 10000 (10 seconds).

  1. // If an operation is buffered for more than 1 second, throw an error.
  2. const schema = new Schema({..}, { bufferTimeoutMS: 1000 });

option: capped

Mongoose supports MongoDBs capped collections. To specify the underlying MongoDB collection be capped, set the capped option to the maximum size of the collection in bytes.

  1. new Schema({..}, { capped: 1024 });

The capped option may also be set to an object if you want to pass additional options like max or autoIndexId. In this case you must explicitly pass the size option, which is required.

  1. new Schema({..}, { capped: { size: 1024, max: 1000, autoIndexId: true } });

option: collection

Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. Set this option if you need a different name for your collection.

  1. const dataSchema = new Schema({..}, { collection: 'data' });

option: discriminatorKey

When you define a discriminator, Mongoose adds a path to your schema that stores which discriminator a document is an instance of. By default, Mongoose adds an __t path, but you can set discriminatorKey to overwrite this default.

  1. const baseSchema = new Schema({}, { discriminatorKey: 'type' });
  2. const BaseModel = mongoose.model('Test', baseSchema);
  3. const personSchema = new Schema({ name: String });
  4. const PersonModel = BaseModel.discriminator('Person', personSchema);
  5. const doc = new PersonModel({ name: 'James T. Kirk' });
  6. // Without `discriminatorKey`, Mongoose would store the discriminator
  7. // key in `__t` instead of `type`
  8. doc.type; // 'Person'

option: id

Mongoose assigns each of your schemas an id virtual getter by default which returns the document’s _id field cast to a string, or in the case of ObjectIds, its hexString. If you don’t want an id getter added to your schema, you may disable it by passing this option at schema construction time.

  1. // default behavior
  2. const schema = new Schema({ name: String });
  3. const Page = mongoose.model('Page', schema);
  4. const p = new Page({ name: 'mongodb.org' });
  5. console.log(p.id); // '50341373e894ad16347efe01'
  6. // disabled id
  7. const schema = new Schema({ name: String }, { id: false });
  8. const Page = mongoose.model('Page', schema);
  9. const p = new Page({ name: 'mongodb.org' });
  10. console.log(p.id); // undefined

option: _id

Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assigned is an ObjectId to coincide with MongoDB’s default behavior. If you don’t want an _id added to your schema at all, you may disable it using this option.

You can only use this option on subdocuments. Mongoose can’t save a document without knowing its id, so you will get an error if you try to save a document without an _id.

  1. // default behavior
  2. const schema = new Schema({ name: String });
  3. const Page = mongoose.model('Page', schema);
  4. const p = new Page({ name: 'mongodb.org' });
  5. console.log(p); // { _id: '50341373e894ad16347efe01', name: 'mongodb.org' }
  6. // disabled _id
  7. const childSchema = new Schema({ name: String }, { _id: false });
  8. const parentSchema = new Schema({ children: [childSchema] });
  9. const Model = mongoose.model('Model', parentSchema);
  10. Model.create({ children: [{ name: 'Luke' }] }, (error, doc) => {
  11. // doc.children[0]._id will be undefined
  12. });

option: minimize

Mongoose will, by default, “minimize” schemas by removing empty objects.

  1. const schema = new Schema({ name: String, inventory: {} });
  2. const Character = mongoose.model('Character', schema);
  3. // will store `inventory` field if it is not empty
  4. const frodo = new Character({ name: 'Frodo', inventory: { ringOfPower: 1 }});
  5. await frodo.save();
  6. let doc = await Character.findOne({ name: 'Frodo' }).lean();
  7. doc.inventory; // { ringOfPower: 1 }
  8. // will not store `inventory` field if it is empty
  9. const sam = new Character({ name: 'Sam', inventory: {}});
  10. await sam.save();
  11. doc = await Character.findOne({ name: 'Sam' }).lean();
  12. doc.inventory; // undefined

This behavior can be overridden by setting minimize option to false. It will then store empty objects.

  1. const schema = new Schema({ name: String, inventory: {} }, { minimize: false });
  2. const Character = mongoose.model('Character', schema);
  3. // will store `inventory` if empty
  4. const sam = new Character({ name: 'Sam', inventory: {} });
  5. await sam.save();
  6. doc = await Character.findOne({ name: 'Sam' }).lean();
  7. doc.inventory; // {}

To check whether an object is empty, you can use the $isEmpty() helper:

  1. const sam = new Character({ name: 'Sam', inventory: {} });
  2. sam.$isEmpty('inventory'); // true
  3. sam.inventory.barrowBlade = 1;
  4. sam.$isEmpty('inventory'); // false

option: read

Allows setting query#read options at the schema level, providing us a way to apply default ReadPreferences to all queries derived from a model.

  1. const schema = new Schema({..}, { read: 'primary' }); // also aliased as 'p'
  2. const schema = new Schema({..}, { read: 'primaryPreferred' }); // aliased as 'pp'
  3. const schema = new Schema({..}, { read: 'secondary' }); // aliased as 's'
  4. const schema = new Schema({..}, { read: 'secondaryPreferred' }); // aliased as 'sp'
  5. const schema = new Schema({..}, { read: 'nearest' }); // aliased as 'n'

The alias of each pref is also permitted so instead of having to type out ‘secondaryPreferred’ and getting the spelling wrong, we can simply pass ‘sp’.

The read option also allows us to specify tag sets. These tell the driver from which members of the replica-set it should attempt to read. Read more about tag sets here and here.

NOTE: you may also specify the driver read pref strategy option when connecting:

  1. // pings the replset members periodically to track network latency
  2. const options = { replset: { strategy: 'ping' }};
  3. mongoose.connect(uri, options);
  4. const schema = new Schema({..}, { read: ['nearest', { disk: 'ssd' }] });
  5. mongoose.model('JellyBean', schema);

option: writeConcern

Allows setting write concern at the schema level.

  1. const schema = new Schema({ name: String }, {
  2. writeConcern: {
  3. w: 'majority',
  4. j: true,
  5. wtimeout: 1000
  6. }
  7. });

option: shardKey

The shardKey option is used when we have a sharded MongoDB architecture. Each sharded collection is given a shard key which must be present in all insert/update operations. We just need to set this schema option to the same shard key and we’ll be all set.

  1. new Schema({ .. }, { shardKey: { tag: 1, name: 1 }})

Note that Mongoose does not send the shardcollection command for you. You must configure your shards yourself.

option: strict

The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db.

  1. const thingSchema = new Schema({..})
  2. const Thing = mongoose.model('Thing', thingSchema);
  3. const thing = new Thing({ iAmNotInTheSchema: true });
  4. thing.save(); // iAmNotInTheSchema is not saved to the db
  5. // set to false..
  6. const thingSchema = new Schema({..}, { strict: false });
  7. const thing = new Thing({ iAmNotInTheSchema: true });
  8. thing.save(); // iAmNotInTheSchema is now saved to the db!!

This also affects the use of doc.set() to set a property value.

  1. const thingSchema = new Schema({..})
  2. const Thing = mongoose.model('Thing', thingSchema);
  3. const thing = new Thing;
  4. thing.set('iAmNotInTheSchema', true);
  5. thing.save(); // iAmNotInTheSchema is not saved to the db

This value can be overridden at the model instance level by passing a second boolean argument:

  1. const Thing = mongoose.model('Thing');
  2. const thing = new Thing(doc, true); // enables strict mode
  3. const thing = new Thing(doc, false); // disables strict mode

The strict option may also be set to "throw" which will cause errors to be produced instead of dropping the bad data.

NOTE: Any key/val set on the instance that does not exist in your schema is always ignored, regardless of schema option.

  1. const thingSchema = new Schema({..})
  2. const Thing = mongoose.model('Thing', thingSchema);
  3. const thing = new Thing;
  4. thing.iAmNotInTheSchema = true;
  5. thing.save(); // iAmNotInTheSchema is never saved to the db

option: strictQuery

For backwards compatibility, the strict option does not apply to the filter parameter for queries.

  1. const mySchema = new Schema({ field: Number }, { strict: true });
  2. const MyModel = mongoose.model('Test', mySchema);
  3. // Mongoose will **not** filter out `notInSchema: 1`, despite `strict: true`
  4. MyModel.find({ notInSchema: 1 });

The strict option does apply to updates.

  1. // Mongoose will strip out `notInSchema` from the update if `strict` is
  2. // not `false`
  3. MyModel.updateMany({}, { $set: { notInSchema: 1 } });

Mongoose has a separate strictQuery option to toggle strict mode for the filter parameter to queries.

  1. const mySchema = new Schema({ field: Number }, {
  2. strict: true,
  3. strictQuery: true // Turn on strict mode for query filters
  4. });
  5. const MyModel = mongoose.model('Test', mySchema);
  6. // Mongoose will strip out `notInSchema: 1` because `strictQuery` is `true`
  7. MyModel.find({ notInSchema: 1 });

option: toJSON

Exactly the same as the toObject option but only applies when the document’s toJSON method is called.

  1. const schema = new Schema({ name: String });
  2. schema.path('name').get(function (v) {
  3. return v + ' is my name';
  4. });
  5. schema.set('toJSON', { getters: true, virtuals: false });
  6. const M = mongoose.model('Person', schema);
  7. const m = new M({ name: 'Max Headroom' });
  8. console.log(m.toObject()); // { _id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom' }
  9. console.log(m.toJSON()); // { _id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom is my name' }
  10. // since we know toJSON is called whenever a js object is stringified:
  11. console.log(JSON.stringify(m)); // { "_id": "504e0cd7dd992d9be2f20b6f", "name": "Max Headroom is my name" }

To see all available toJSON/toObject options, read this.

option: toObject

Documents have a toObject method which converts the mongoose document into a plain JavaScript object. This method accepts a few options. Instead of applying these options on a per-document basis, we may declare the options at the schema level and have them applied to all of the schema’s documents by default.

To have all virtuals show up in your console.log output, set the toObject option to { getters: true }:

  1. const schema = new Schema({ name: String });
  2. schema.path('name').get(function(v) {
  3. return v + ' is my name';
  4. });
  5. schema.set('toObject', { getters: true });
  6. const M = mongoose.model('Person', schema);
  7. const m = new M({ name: 'Max Headroom' });
  8. console.log(m); // { _id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom is my name' }

To see all available toObject options, read this.

option: typeKey

By default, if you have an object with key ‘type’ in your schema, mongoose will interpret it as a type declaration.

  1. // Mongoose interprets this as 'loc is a String'
  2. const schema = new Schema({ loc: { type: String, coordinates: [Number] } });

However, for applications like geoJSON, the ‘type’ property is important. If you want to control which key mongoose uses to find type declarations, set the ‘typeKey’ schema option.

  1. const schema = new Schema({
  2. // Mongoose interpets this as 'loc is an object with 2 keys, type and coordinates'
  3. loc: { type: String, coordinates: [Number] },
  4. // Mongoose interprets this as 'name is a String'
  5. name: { $type: String }
  6. }, { typeKey: '$type' }); // A '$type' key means this object is a type declaration

option: validateBeforeSave

By default, documents are automatically validated before they are saved to the database. This is to prevent saving an invalid document. If you want to handle validation manually, and be able to save objects which don’t pass validation, you can set validateBeforeSave to false.

  1. const schema = new Schema({ name: String });
  2. schema.set('validateBeforeSave', false);
  3. schema.path('name').validate(function (value) {
  4. return value != null;
  5. });
  6. const M = mongoose.model('Person', schema);
  7. const m = new M({ name: null });
  8. m.validate(function(err) {
  9. console.log(err); // Will tell you that null is not allowed.
  10. });
  11. m.save(); // Succeeds despite being invalid

option: versionKey

The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The versionKey option is a string that represents the path to use for versioning. The default is __v. If this conflicts with your application you can configure as such:

  1. const schema = new Schema({ name: 'string' });
  2. const Thing = mongoose.model('Thing', schema);
  3. const thing = new Thing({ name: 'mongoose v3' });
  4. await thing.save(); // { __v: 0, name: 'mongoose v3' }
  5. // customized versionKey
  6. new Schema({..}, { versionKey: '_somethingElse' })
  7. const Thing = mongoose.model('Thing', schema);
  8. const thing = new Thing({ name: 'mongoose v3' });
  9. thing.save(); // { _somethingElse: 0, name: 'mongoose v3' }

Note that Mongoose’s default versioning is not a full optimistic concurrency solution. Mongoose’s default versioning only operates on arrays as shown below.

  1. // 2 copies of the same document
  2. const doc1 = await Model.findOne({ _id });
  3. const doc2 = await Model.findOne({ _id });
  4. // Delete first 3 comments from `doc1`
  5. doc1.comments.splice(0, 3);
  6. await doc1.save();
  7. // The below `save()` will throw a VersionError, because you're trying to
  8. // modify the comment at index 1, and the above `splice()` removed that
  9. // comment.
  10. doc2.set('comments.1.body', 'new comment');
  11. await doc2.save();

If you need optimistic concurrency support for save(), you can set the optimisticConcurrency option

Document versioning can also be disabled by setting the versionKey to false. DO NOT disable versioning unless you know what you are doing.

  1. new Schema({..}, { versionKey: false });
  2. const Thing = mongoose.model('Thing', schema);
  3. const thing = new Thing({ name: 'no versioning please' });
  4. thing.save(); // { name: 'no versioning please' }

Mongoose only updates the version key when you use save(). If you use update(), findOneAndUpdate(), etc. Mongoose will not update the version key. As a workaround, you can use the below middleware.

  1. schema.pre('findOneAndUpdate', function() {
  2. const update = this.getUpdate();
  3. if (update.__v != null) {
  4. delete update.__v;
  5. }
  6. const keys = ['$set', '$setOnInsert'];
  7. for (const key of keys) {
  8. if (update[key] != null && update[key].__v != null) {
  9. delete update[key].__v;
  10. if (Object.keys(update[key]).length === 0) {
  11. delete update[key];
  12. }
  13. }
  14. }
  15. update.$inc = update.$inc || {};
  16. update.$inc.__v = 1;
  17. });

option: optimisticConcurrency

Optimistic concurrency is a strategy to ensure the document you’re updating didn’t change between when you loaded it using find() or findOne(), and when you update it using save().

For example, suppose you have a House model that contains a list of photos, and a status that represents whether this house shows up in searches. Suppose that a house that has status 'APPROVED' must have at least two photos. You might implement the logic of approving a house document as shown below:

  1. async function markApproved(id) {
  2. const house = await House.findOne({ _id });
  3. if (house.photos.length < 2) {
  4. throw new Error('House must have at least two photos!');
  5. }
  6. house.status = 'APPROVED';
  7. await house.save();
  8. }

The markApproved() function looks right in isolation, but there might be a potential issue: what if another function removes the house’s photos between the findOne() call and the save() call? For example, the below code will succeed:

  1. const house = await House.findOne({ _id });
  2. if (house.photos.length < 2) {
  3. throw new Error('House must have at least two photos!');
  4. }
  5. const house2 = await House.findOne({ _id });
  6. house2.photos = [];
  7. await house2.save();
  8. // Marks the house as 'APPROVED' even though it has 0 photos!
  9. house.status = 'APPROVED';
  10. await house.save();

If you set the optimisticConcurrency option on the House model’s schema, the above script will throw an error.

  1. const House = mongoose.model('House', Schema({
  2. status: String,
  3. photos: [String]
  4. }, { optimisticConcurrency: true }));
  5. const house = await House.findOne({ _id });
  6. if (house.photos.length < 2) {
  7. throw new Error('House must have at least two photos!');
  8. }
  9. const house2 = await House.findOne({ _id });
  10. house2.photos = [];
  11. await house2.save();
  12. // Throws 'VersionError: No matching document found for id "..." version 0'
  13. house.status = 'APPROVED';
  14. await house.save();

option: collation

Sets a default collation for every query and aggregation. Here’s a beginner-friendly overview of collations.

  1. const schema = new Schema({
  2. name: String
  3. }, { collation: { locale: 'en_US', strength: 1 } });
  4. const MyModel = db.model('MyModel', schema);
  5. MyModel.create([{ name: 'val' }, { name: 'Val' }]).
  6. then(() => {
  7. return MyModel.find({ name: 'val' });
  8. }).
  9. then((docs) => {
  10. // `docs` will contain both docs, because `strength: 1` means
  11. // MongoDB will ignore case when matching.
  12. });

option: skipVersioning

skipVersioning allows excluding paths from versioning (i.e., the internal revision will not be incremented even if these paths are updated). DO NOT do this unless you know what you’re doing. For subdocuments, include this on the parent document using the fully qualified path.

  1. new Schema({..}, { skipVersioning: { dontVersionMe: true } });
  2. thing.dontVersionMe.push('hey');
  3. thing.save(); // version is not incremented

option: timestamps

The timestamps option tells mongoose to assign createdAt and updatedAt fields to your schema. The type assigned is Date.

By default, the names of the fields are createdAt and updatedAt. Customize the field names by setting timestamps.createdAt and timestamps.updatedAt.

  1. const thingSchema = new Schema({..}, { timestamps: { createdAt: 'created_at' } });
  2. const Thing = mongoose.model('Thing', thingSchema);
  3. const thing = new Thing();
  4. await thing.save(); // `created_at` & `updatedAt` will be included
  5. // With updates, Mongoose will add `updatedAt` to `$set`
  6. await Thing.updateOne({}, { $set: { name: 'Test' } });
  7. // If you set upsert: true, Mongoose will add `created_at` to `$setOnInsert` as well
  8. await Thing.findOneAndUpdate({}, { $set: { name: 'Test2' } });
  9. // Mongoose also adds timestamps to bulkWrite() operations
  10. // See https://mongoosejs.com/docs/5.x/docs/api.html#model_Model.bulkWrite
  11. await Thing.bulkWrite([
  12. insertOne: {
  13. document: {
  14. name: 'Jean-Luc Picard',
  15. ship: 'USS Stargazer'
  16. // Mongoose will add `created_at` and `updatedAt`
  17. }
  18. },
  19. updateOne: {
  20. filter: { name: 'Jean-Luc Picard' },
  21. update: {
  22. $set: {
  23. ship: 'USS Enterprise'
  24. // Mongoose will add `updatedAt`
  25. }
  26. }
  27. }
  28. ]);

By default, Mongoose uses new Date() to get the current time. If you want to overwrite the function Mongoose uses to get the current time, you can set the timestamps.currentTime option. Mongoose will call the timestamps.currentTime function whenever it needs to get the current time.

  1. const schema = Schema({
  2. createdAt: Number,
  3. updatedAt: Number,
  4. name: String
  5. }, {
  6. // Make Mongoose use Unix time (seconds since Jan 1, 1970)
  7. timestamps: { currentTime: () => Math.floor(Date.now() / 1000) }
  8. });

option: useNestedStrict

Write operations like update(), updateOne(), updateMany(), and findOneAndUpdate() only check the top-level schema’s strict mode setting.

  1. const childSchema = new Schema({}, { strict: false });
  2. const parentSchema = new Schema({ child: childSchema }, { strict: 'throw' });
  3. const Parent = mongoose.model('Parent', parentSchema);
  4. Parent.update({}, { 'child.name': 'Luke Skywalker' }, (error) => {
  5. // Error because parentSchema has `strict: throw`, even though
  6. // `childSchema` has `strict: false`
  7. });
  8. const update = { 'child.name': 'Luke Skywalker' };
  9. const opts = { strict: false };
  10. Parent.update({}, update, opts, function(error) {
  11. // This works because passing `strict: false` to `update()` overwrites
  12. // the parent schema.
  13. });

If you set useNestedStrict to true, mongoose will use the child schema’s strict option for casting updates.

  1. const childSchema = new Schema({}, { strict: false });
  2. const parentSchema = new Schema({ child: childSchema },
  3. { strict: 'throw', useNestedStrict: true });
  4. const Parent = mongoose.model('Parent', parentSchema);
  5. Parent.update({}, { 'child.name': 'Luke Skywalker' }, error => {
  6. // Works!
  7. });

option: selectPopulatedPaths

By default, Mongoose will automatically select() any populated paths for you, unless you explicitly exclude them.

  1. const bookSchema = new Schema({
  2. title: 'String',
  3. author: { type: 'ObjectId', ref: 'Person' }
  4. });
  5. const Book = mongoose.model('Book', bookSchema);
  6. // By default, Mongoose will add `author` to the below `select()`.
  7. await Book.find().select('title').populate('author');
  8. // In other words, the below query is equivalent to the above
  9. await Book.find().select('title author').populate('author');

To opt out of selecting populated fields by default, set selectPopulatedPaths to false in your schema.

  1. const bookSchema = new Schema({
  2. title: 'String',
  3. author: { type: 'ObjectId', ref: 'Person' }
  4. }, { selectPopulatedPaths: false });
  5. const Book = mongoose.model('Book', bookSchema);
  6. // Because `selectPopulatedPaths` is false, the below doc will **not**
  7. // contain an `author` property.
  8. const doc = await Book.findOne().select('title').populate('author');

option: storeSubdocValidationError

For legacy reasons, when there is a validation error in subpath of a single nested schema, Mongoose will record that there was a validation error in the single nested schema path as well. For example:

  1. const childSchema = new Schema({ name: { type: String, required: true } });
  2. const parentSchema = new Schema({ child: childSchema });
  3. const Parent = mongoose.model('Parent', parentSchema);
  4. // Will contain an error for both 'child.name' _and_ 'child'
  5. new Parent({ child: {} }).validateSync().errors;

Set the storeSubdocValidationError to false on the child schema to make Mongoose only reports the parent error.

  1. const childSchema = new Schema({
  2. name: { type: String, required: true }
  3. }, { storeSubdocValidationError: false }); // <-- set on the child schema
  4. const parentSchema = new Schema({ child: childSchema });
  5. const Parent = mongoose.model('Parent', parentSchema);
  6. // Will only contain an error for 'child.name'
  7. new Parent({ child: {} }).validateSync().errors;

With ES6 Classes

Schemas have a loadClass() method that you can use to create a Mongoose schema from an ES6 class:

Here’s an example of using loadClass() to create a schema from an ES6 class:

  1. class MyClass {
  2. myMethod() { return 42; }
  3. static myStatic() { return 42; }
  4. get myVirtual() { return 42; }
  5. }
  6. const schema = new mongoose.Schema();
  7. schema.loadClass(MyClass);
  8. console.log(schema.methods); // { myMethod: [Function: myMethod] }
  9. console.log(schema.statics); // { myStatic: [Function: myStatic] }
  10. console.log(schema.virtuals); // { myVirtual: VirtualType { ... } }

Pluggable

Schemas are also pluggable which allows us to package up reusable features into plugins that can be shared with the community or just between your projects.

Further Reading

Here’s an alternative introduction to Mongoose schemas.

To get the most out of MongoDB, you need to learn the basics of MongoDB schema design. SQL schema design (third normal form) was designed to minimize storage costs, whereas MongoDB schema design is about making common queries as fast as possible. The 6 Rules of Thumb for MongoDB Schema Design blog series is an excellent resource for learning the basic rules for making your queries fast.

Users looking to master MongoDB schema design in Node.js should look into The Little MongoDB Schema Design Book by Christian Kvalheim, the original author of the MongoDB Node.js driver. This book shows you how to implement performant schemas for a laundry list of use cases, including e-commerce, wikis, and appointment bookings.

Next Up

Now that we’ve covered Schemas, let’s take a look at SchemaTypes.