Schema constructor.
var child = new Schema({ name: String });
var schema = new Schema({ name: String, age: Number, children: [child] });
var Tree = mongoose.model('Tree', schema);
// setting schema options
new Schema({ name: String }, { _id: false, autoIndex: false })
null
true
true
false
. If true, Mongoose adds createdAt
and updatedAt
properties to your schema and manages those properties for you.excludeIndexes
: bool - defaults to false
. If true
, skip building indexes on this schema's paths.When nesting schemas, (children
in the example above), always declare the child schema first before passing it into its parent.
The various built-in Mongoose Schema Types.
var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
Using this exposed access to the Mixed
SchemaType, we can use them in our schema.
var Mixed = mongoose.Schema.Types.Mixed;
new mongoose.Schema({ _user: Mixed })
The allowed index types
Adds key path / schema type pairs to this schema.
const ToySchema = new Schema();
ToySchema.add({ name: 'string', color: 'string', price: 'number' });
const TurboManSchema = new Schema();
// You can also `add()` another schema and copy over all paths, virtuals,
// getters, setters, indexes, methods, and statics.
TurboManSchema.add(ToySchema).add({ year: Number });
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.
Returns a deep copy of the schema
const schema = new Schema({ name: String });
const clone = schema.clone();
clone === schema; // false
clone.path('name'); // SchemaString { ... }
Iterates the schemas paths similar to Array#forEach.
The callback is passed the pathname and the schemaType instance.
const userSchema = new Schema({ name: String, registeredAt: Date });
userSchema.eachPath((pathname, schematype) => {
// Prints twice:
// name SchemaString { ... }
// registeredAt SchemaDate { ... }
console.log(pathname, schematype);
});
Gets a schema option.
schema.get('strict'); // true
schema.set('strict', false);
schema.get('strict'); // false
createIndex()
function expires
option into seconds for the expireAfterSeconds
in the above link. Defines an index (most likely compound) for this schema.
schema.index({ first: 1, last: -1 })
Returns a list of indexes that this schema declares, via schema.index()
or by index: true
in a path's options.
const userSchema = new Schema({
email: { type: String, required: true, unique: true },
registeredAt: { type: Date, index: true }
});
// [ [ { email: 1 }, { unique: true, background: true } ],
// [ { registeredAt: 1 }, { background: true } ] ]
userSchema.indexes();
Loads an ES6 class into a schema. Maps setters + getters, static methods, and instance methods to schema virtuals, statics, and methods.
const md5 = require('md5');
const userSchema = new Schema({ email: String });
class UserClass {
// `gravatarImage` becomes a virtual
get gravatarImage() {
const hash = md5(this.email.toLowerCase());
return `https://www.gravatar.com/avatar/${hash}`;
}
// `getProfileUrl()` becomes a document method
getProfileUrl() {
return `https://mysite.com/${this.email}`;
}
// `findByEmail()` becomes a static
static findByEmail(email) {
return this.findOne({ email });
}
}
// `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
// and a `findByEmail()` static
userSchema.loadClass(UserClass);
Adds an instance method to documents constructed from Models compiled from this schema.
var schema = kittySchema = new Schema(..);
schema.method('meow', function () {
console.log('meeeeeoooooooooooow');
})
var Kitty = mongoose.model('Kitty', schema);
var fizz = new Kitty;
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.
schema.method({
purr: function () {}
, scratch: function () {}
});
// later
fizz.purr();
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
The original object passed to the schema constructor
var schema = new Schema({ a: String }).add({ b: String });
schema.obj; // { a: String }
Gets/sets schema paths.
Sets a path (if arity 2) Gets a path (if arity 1)
schema.path('name') // returns a SchemaType
schema.path('name', Number) // changes the schemaType of `name` to Number
Returns the pathType of path
for this schema.
Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.
const s = new Schema({ name: String, nested: { foo: String } });
s.virtual('foo').get(() => 42);
s.pathType('name'); // "real"
s.pathType('nested'); // "nested"
s.pathType('foo'); // "virtual"
s.pathType('fail'); // "adhocOrUndefined"
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.
const schema = new Schema({ name: String }, { _id: false });
schema.paths; // { name: SchemaString { ... } }
schema.add({ age: Number });
schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }
this.options
if not set. Returns a new schema that has the picked paths
from this schema.
This method is analagous to Lodash's pick()
function for Mongoose schemas.
const schema = Schema({ name: String, age: Number });
// Creates a new schema with the same `name` path as `schema`,
// but no `age` path.
const newSchema = schema.pick(['name']);
newSchema.path('name'); // SchemaString { ... }
newSchema.path('age'); // undefined
Registers a plugin for this schema.
const s = new Schema({ name: String });
s.plugin(schema => console.log(schema.path('name').path));
mongoose.model('Test', s); // Prints 'name'
name
is a hook for both document and query middleware, set to true
to run on document middleware. name
is a hook for both document and query middleware, set to true
to run on query middleware. Defines a post hook for the document
var schema = new Schema(..); schema.post('save', function (doc) { console.log('this fired after a document was saved'); }); schema.post('find', function(docs) { console.log('this fired after you ran a find query'); }); schema.post(/Many$/, function(res) { console.log('this fired after you ran `updateMany()` or `deleteMany()`); }); var Model = mongoose.model('Model', schema); var m = new Model(..); m.save(function(err) { console.log('this fires after the `post` hook'); }); m.find(function(err, docs) { console.log('this fires after the post find hook'); });
name
is a hook for both document and query middleware, set to true
to run on document middleware. name
is a hook for both document and query middleware, set to true
to run on query middleware. Defines a pre hook for the document.
var toySchema = new Schema({ name: String, created: Date });
toySchema.pre('save', function(next) {
if (!this.created) this.created = new Date;
next();
});
toySchema.pre('validate', function(next) {
if (this.name !== 'Woody') this.name = 'Woody';
next();
});
// Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
toySchema.pre(/^find/, function(next) {
console.log(this.getFilter());
});
// Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
console.log(this.getFilter());
});
Adds a method call to the queue.
schema.methods.print = function() { console.log(this); };
schema.queue('print', []); // Print the doc every one is instantiated
const Model = mongoose.model('Test', schema);
new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'
Removes the given path
(or [paths
]).
const schema = new Schema({ name: String, age: Number });
schema.remove('name');
schema.path('name'); // Undefined
schema.path('age'); // SchemaNumber { ... }
Returns an Array of path strings that are required by this schema.
const s = new Schema({
name: { type: String, required: true },
age: { type: String, required: true },
notes: String
});
s.requiredPaths(); // [ 'age', 'name' ]
Sets/gets a schema option.
schema.set('strict'); // 'true' by default
schema.set('strict', false); // Sets 'strict' to false
schema.set('strict'); // 'false'
Adds static "class" methods to Models compiled from this schema.
const schema = new Schema(..);
// Equivalent to `schema.statics.findByName = function(name) {}`;
schema.static('findByName', function(name) {
return this.find({ name: name });
});
const Drink = mongoose.model('Drink', schema);
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.
null
. Otherwise, the populate virtual will be an array. populate()
. Creates a virtual type with the given name.
Returns the virtual type with the given name
.
Reserved document keys.
Keys in this object are names that are rejected in schema declarations because they conflict with Mongoose functionality. If you create a schema using new Schema()
with one of these property names, Mongoose will throw an error.
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.
var schema = new Schema(..);
schema.methods.init = function () {} // potentially breaking
© 2010 LearnBoost
Licensed under the MIT License.
https://mongoosejs.com/docs/api/schema.html