SchemaTypes

SchemaTypes handle definition of path defaults, validation, getters, setters, field selection defaults for queries and other general characteristics for Strings andNumbers. Check out their respective API documentation for more detail.

Following are all valid Schema Types.

Example

  1. var schema = new Schema({
  2. name: String,
  3. binary: Buffer,
  4. living: Boolean,
  5. updated: { type: Date, default: Date.now },
  6. age: { type: Number, min: 18, max: 65 },
  7. mixed: Schema.Types.Mixed,
  8. _someId: Schema.Types.ObjectId,
  9. array: [],
  10. ofString: [String],
  11. ofNumber: [Number],
  12. ofDates: [Date],
  13. ofBuffer: [Buffer],
  14. ofBoolean: [Boolean],
  15. ofMixed: [Schema.Types.Mixed],
  16. ofObjectId: [Schema.Types.ObjectId],
  17. ofArrays: [[]],
  18. ofArrayOfNumbers: [[Number]],
  19. nested: {
  20. stuff: { type: String, lowercase: true, trim: true }
  21. }
  22. })
  23. // example use
  24. var Thing = mongoose.model('Thing', schema);
  25. var m = new Thing;
  26. m.name = 'Statue of Liberty';
  27. m.age = 125;
  28. m.updated = new Date;
  29. m.binary = new Buffer(0);
  30. m.living = false;
  31. m.mixed = { any: { thing: 'i want' } };
  32. m.markModified('mixed');
  33. m._someId = new mongoose.Types.ObjectId;
  34. m.array.push(1);
  35. m.ofString.push("strings!");
  36. m.ofNumber.unshift(1,2,3,4);
  37. m.ofDates.addToSet(new Date);
  38. m.ofBuffer.pop();
  39. m.ofMixed = [1, [], 'three', { four: 5 }];
  40. m.nested.stuff = 'good';
  41. m.save(callback);

SchemaType Options

You can declare a schema type using the type directly, or an object with a type property.

  1. var schema1 = new Schema({
  2. test: String // `test` is a path of type String
  3. });
  4. var schema2 = new Schema({
  5. test: { type: String } // `test` is a path of type string
  6. });

In addition to the type property, you can specify additional properties for a path. For example, if you want to lowercase a string before saving:

  1. var schema2 = new Schema({
  2. test: {
  3. type: String,
  4. lowercase: true // Always convert `test` to lowercase
  5. }
  6. });

The lowercase property only works for strings. There are certain options which apply for all schema types, and some that apply for specific schema types.

All Schema Types
  • required: boolean or function, if true adds a required validator for this property
  • default: Any or function, sets a default value for the path. If the value is a function, the return value of the function is used as the default.
  • select: boolean, specifies default projections for queries
  • validate: function, adds a validator function for this property
  • get: function, defines a custom getter for this property using Object.defineProperty().
  • set: function, defines a custom setter for this property using Object.defineProperty().
  • alias: string, mongoose >= 4.10.0 only. Defines a virtual with the given name that gets/sets this path.
  1. var numberSchema = new Schema({
  2. integerOnly: {
  3. type: Number,
  4. get: v => Math.round(v),
  5. set: v => Math.round(v),
  6. alias: 'i'
  7. }
  8. });
  9. var Number = mongoose.model('Number', numberSchema);
  10. var doc = new Number();
  11. doc.integerOnly = 2.001;
  12. doc.integerOnly; // 2
  13. doc.i; // 2
  14. doc.i = 3.001;
  15. doc.integerOnly; // 3
  16. doc.i; // 3
Indexes

You can also define MongoDB indexes using schema type options.

  • index: boolean, whether to define an index on this property.
  • unique: boolean, whether to define a unique index on this property.
  • sparse: boolean, whether to define a sparse index on this property.
  1. var schema2 = new Schema({
  2. test: {
  3. type: String,
  4. index: true,
  5. unique: true // Unique index. If you specify `unique: true`
  6. // specifying `index: true` is optional if you do `unique: true`
  7. }
  8. });
String
  • lowercase: boolean, whether to always call .toLowerCase() on the value
  • uppercase: boolean, whether to always call .toUpperCase() on the value
  • trim: boolean, whether to always call .trim() on the value
  • match: RegExp, creates a validator that checks if the value matches the given regular expression
  • enum: Array, creates a validator that checks if the value is in the given array.
Number
  • min: Number, creates a validator that checks if the value is greater than or equal to the given minimum.
  • max: Number, creates a validator that checks if the value is less than or equal to the given maximum.
Date
  • min: Date
  • max: Date

Usage notes:

Dates

Built-in Date methods are not hooked into the mongoose change tracking logic which in English means that if you use a Date in your document and modify it with a method like setMonth(), mongoose will be unaware of this change and doc.save() will not persist this modification. If you must modify Date types using built-in methods, tell mongoose about the change with doc.markModified('pathToYourDate') before saving.

  1. var Assignment = mongoose.model('Assignment', { dueDate: Date });
  2. Assignment.findOne(function (err, doc) {
  3. doc.dueDate.setMonth(3);
  4. doc.save(callback); // THIS DOES NOT SAVE YOUR CHANGE
  5. doc.markModified('dueDate');
  6. doc.save(callback); // works
  7. })

Mixed

An “anything goes” SchemaType, its flexibility comes at a trade-off of it being harder to maintain. Mixed is available either through Schema.Types.Mixed or by passing an empty object literal. The following are equivalent:

  1. var Any = new Schema({ any: {} });
  2. var Any = new Schema({ any: Object });
  3. var Any = new Schema({ any: Schema.Types.Mixed });

Since it is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto detect and save those changes. To “tell” Mongoose that the value of a Mixed type has changed, call the.markModified(path) method of the document passing the path to the Mixed type you just changed.

  1. person.anything = { x: [3, 4, { y: "changed" }] };
  2. person.markModified('anything');
  3. person.save(); // anything will now get saved

ObjectIds

To specify a type of ObjectId, useSchema.Types.ObjectId in your declaration.

  1. var mongoose = require('mongoose');
  2. var ObjectId = mongoose.Schema.Types.ObjectId;
  3. var Car = new Schema({ driver: ObjectId });
  4. // or just Schema.ObjectId for backwards compatibility with v2

Arrays

Provide creation of arrays ofSchemaTypes orSub-Documents.

  1. var ToySchema = new Schema({ name: String });
  2. var ToyBox = new Schema({
  3. toys: [ToySchema],
  4. buffers: [Buffer],
  5. string: [String],
  6. numbers: [Number]
  7. // ... etc
  8. });

Note: specifying an empty array is equivalent toMixed. The following all create arrays ofMixed:

  1. var Empty1 = new Schema({ any: [] });
  2. var Empty2 = new Schema({ any: Array });
  3. var Empty3 = new Schema({ any: [Schema.Types.Mixed] });
  4. var Empty4 = new Schema({ any: [{}] });

Arrays implicitly have a default value of `[]` (empty array).

  1. var Toy = mongoose.model('Test', ToySchema);
  2. console.log((new Toy()).toys); // []

To overwrite this default, you need to set the default value to `undefined`

  1. var ToySchema = new Schema({
  2. toys: {
  3. type: [ToySchema],
  4. default: undefined
  5. }
  6. });

If an array is marked as `required`, it must have at least one element.

  1. var ToySchema = new Schema({
  2. toys: {
  3. type: [ToySchema],
  4. required: true
  5. }
  6. });
  7. var Toy = mongoose.model('Toy', ToySchema);
  8. Toy.create({ toys: [] }, function(error) {
  9. console.log(error.errors['toys'].message); // Path "toys" is required.
  10. });

Creating Custom Types

Mongoose can also be extended with custom SchemaTypes. Search theplugins site for compatible types likemongoose-long, mongoose-int32 andother|types.

The `schema.path()` Function

The schema.path() function returns the instantiated schema type for a given path.

  1. var sampleSchema = new Schema({ name: { type: String, required: true } });
  2. console.log(sampleSchema.path('name'));
  3. // Output looks like:
  4. /**
  5. * SchemaString {
  6. * enumValues: [],
  7. * regExp: null,
  8. * path: 'name',
  9. * instance: 'String',
  10. * validators: ...
  11. */

You can use this function to inspect the schema type for a given path, including what validators it has and what the type is.

Next Up

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