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 2.x to 3.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. var mongoose = require('mongoose');
  2. var Schema = mongoose.Schema;
  3. var blogSchema = new Schema({
  4. title: 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 blogSchema defines a property in our documents which will be cast to its associated SchemaType. For example, we’ve defined a title which will be cast to the String SchemaType and date which will be cast to a Date SchemaType. Keys may also be assigned nested objects containing further key/type definitions (e.g. the `meta` property above).

The permitted SchemaTypes are

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array

Read more about them 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. var Blog = mongoose.model('Blog', blogSchema);
  2. // ready to go!

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 too.

  1. // define a schema
  2. var 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 this.model('Animal').find({ type: this.type }, cb);
  6. }

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

  1. var Animal = mongoose.model('Animal', animalSchema);
  2. var dog = new Animal({ type: 'dog' });
  3. dog.findSimilarTypes(function (err, dogs) {
  4. console.log(dogs); // woof
  5. });

Overwriting a default mongoose document method may lead to unpredictible results. See this for more details.

Statics

Adding static methods to a Model is simple as well. Continuing with our animalSchema:

  1. // assign a function to the "statics" object of our animalSchema
  2. animalSchema.statics.findByName = function (name, cb) {
  3. this.find({ name: new RegExp(name, 'i') }, cb);
  4. }
  5. var Animal = mongoose.model('Animal', animalSchema);
  6. Animal.findByName('fido', function (err, animals) {
  7. console.log(animals);
  8. });

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. var 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 ensureIndex for each defined index in your schema. 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.

  1. animalSchema.set('autoIndex', false);
  2. // or
  3. new Schema({..}, { autoIndex: false });

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 settings are useful for de-composing a single value into multiple values for storage.

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

Suppose we want to log the full name of bad. We could do this manually like so:

  1. console.log(bad.name.first + ' ' + bad.name.last); // Walter White

Or we could define a virtual property getter on our personSchema so we don’t need to write out this string concatenation mess each time:

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

Now, when we access our virtual “name.full” property, our getter function will be invoked and the value returned:

  1. console.log('%s is insane', bad.name.full); // Walter White is insane

Note that if the resulting record is converted to an object or JSON, virtuals are not included by default. Pass virtuals : true to either toObject() or to toJSON() to have them returned.

It would also be nice to be able to set this.name.first and this.name.last by setting this.name.full. For example, if we wanted to change bad‘s name.first and name.last to ‘Breaking’ and ‘Bad’ respectively, it’d be nice to just:

  1. bad.name.full = 'Breaking Bad';

Mongoose lets you do this as well through its virtual property setters:

  1. personSchema.virtual('name.full').set(function (name) {
  2. var split = name.split(' ');
  3. this.name.first = split[0];
  4. this.name.last = split[1];
  5. });
  6. ...
  7. mad.name.full = 'Breaking Bad';
  8. console.log(mad.name.first); // Breaking
  9. console.log(mad.name.last); // Bad

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.

Options

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

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

Valid options:

option: autoIndex

At application startup, Mongoose sends an ensureIndex command for each index declared in your Schema. As of Mongoose v3, indexes are created in the background by default. If you wish to disable the auto-creation feature and manually handle when indexes are created, set your Schemas autoIndex option to false and use the ensureIndexes method on your model.

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

option: bufferCommands

When running with the drivers autoReconnect option disabled and connected to a single mongod (non-replica-set), mongoose buffers commands when the connection goes down until you manually reconnect. To disable mongoose buffering under these conditions, set this option to false.

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

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. var dataSchema = new Schema({..}, { collection: 'data' });

option: id

Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _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 passing this option at schema construction time.

  1. // default behavior
  2. var schema = new Schema({ name: String });
  3. var Page = mongoose.model('Page', schema);
  4. var p = new Page({ name: 'mongodb.org' });
  5. console.log(p.id); // '50341373e894ad16347efe01'
  6. // disabled id
  7. var schema = new Schema({ name: String }, { id: false });
  8. var Page = mongoose.model('Page', schema);
  9. var 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 assiged is an ObjectId to coincide with MongoDBs default behavior. If you don’t want an _id added to your schema at all, you may disable it using this option.

Pass this option during schema construction to prevent documents from getting an _id created by Mongoose (parent documents will still have an _id created by MongoDB when inserted). Passing the option later using Schema.set('_id', false) will not work. See issue #1512.

  1. // default behavior
  2. var schema = new Schema({ name: String });
  3. var Page = mongoose.model('Page', schema);
  4. var p = new Page({ name: 'mongodb.org' });
  5. console.log(p); // { _id: '50341373e894ad16347efe01', name: 'mongodb.org' }
  6. // disabled _id
  7. var schema = new Schema({ name: String }, { _id: false });
  8. // Don't set _id to false after schema construction as in
  9. // var schema = new Schema({ name: String });
  10. // schema.set('_id', false);
  11. var Page = mongoose.model('Page', schema);
  12. var p = new Page({ name: 'mongodb.org' });
  13. console.log(p); // { name: 'mongodb.org' }
  14. // MongoDB will create the _id when inserted
  15. p.save(function (err) {
  16. if (err) return handleError(err);
  17. Page.findById(p, function (err, doc) {
  18. if (err) return handleError(err);
  19. console.log(doc); // { name: 'mongodb.org', _id: '50341373e894ad16347efe12' }
  20. })
  21. })

Note that currently you must disable the _id

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. var schema = new Schema({..}, { read: 'primary' }); // also aliased as 'p'
  2. var schema = new Schema({..}, { read: 'primaryPreferred' }); // aliased as 'pp'
  3. var schema = new Schema({..}, { read: 'secondary' }); // aliased as 's'
  4. var schema = new Schema({..}, { read: 'secondaryPreferred' }); // aliased as 'sp'
  5. var 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. var options = { replset: { strategy: 'ping' }};
  3. mongoose.connect(uri, options);
  4. var schema = new Schema({..}, { read: ['nearest', { disk: 'ssd' }] });
  5. mongoose.model('JellyBean', schema);

option: safe

This option is passed to MongoDB with all operations and specifies if errors should be returned to our callbacks as well as tune write behavior.

  1. var safe = true;
  2. new Schema({ .. }, { safe: safe });

By default this is set to true for all schemas which guarentees that any occurring error gets passed back to our callback. By setting safe to something else like { j: 1, w: 2, wtimeout: 10000 } we can guarantee the write was committed to the MongoDB journal (j: 1), at least 2 replicas (w: 2), and that the write will timeout if it takes longer than 10 seconds (wtimeout: 10000). Errors will still be passed to our callback.

NOTE: In 3.6.x, you also need to turn versioning off. In 3.7.x and above, versioning will automatically be disabled when safe is set to false

**NOTE: this setting overrides any setting specified by passing db options while creating a connection.

There are other write concerns like { w: "majority" } too. See the MongoDB docs for more details.

  1. var safe = { w: "majority", wtimeout: 10000 };
  2. new Schema({ .. }, { safe: safe });

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. var thingSchema = new Schema({..})
  2. var Thing = mongoose.model('Thing', thingSchema);
  3. var thing = new Thing({ iAmNotInTheSchema: true });
  4. thing.save(); // iAmNotInTheSchema is not saved to the db
  5. // set to false..
  6. var thingSchema = new Schema({..}, { strict: false });
  7. var 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. var thingSchema = new Schema({..})
  2. var Thing = mongoose.model('Thing', thingSchema);
  3. var 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. var Thing = mongoose.model('Thing');
  2. var thing = new Thing(doc, true); // enables strict mode
  3. var 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: do not set to false unless you have good reason.

NOTE: in mongoose v2 the default was false.

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

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

option: toJSON

Exactly the same as the toObject option but only applies when the documents toJSON method is called.

  1. var 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. var M = mongoose.model('Person', schema);
  7. var 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 here and have it applied to all of this schemas documents by default.

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

  1. var 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. var M = mongoose.model('Person', schema);
  7. var 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: 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 name of this document property is configurable. The default is __v. If this conflicts with your application you can configure as such:

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

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. var Thing = mongoose.model('Thing', schema);
  3. var thing = new Thing({ name: 'no versioning please' });
  4. thing.save(); // { name: 'no versioning please' }

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.

Next Up

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