Mongoose.prototype.model()
Parameters
name «String|Function» model name or class extending Model
[schema] «Schema» the schema to use.
[collection] «String» name (optional, inferred from model name)
[skipInit] «Boolean|Object» whether to skip initialization (defaults to false). If an object, treated as options.
Returns:
- «Model» The model associated with
name
. Mongoose will create the model if it doesn’t already exist.
Defines a model or retrieves it.
Models defined on the mongoose
instance are available to all connection created by the same mongoose
instance.
If you call mongoose.model()
with twice the same name but a different schema, you will get an OverwriteModelError
. If you call mongoose.model()
with the same name and same schema, you’ll get the same schema back.
Example:
const mongoose = require('mongoose');
// define an Actor model with this mongoose instance
const schema = new Schema({ name: String });
mongoose.model('Actor', schema);
// create a new connection
const conn = mongoose.createConnection(..);
// create Actor model
const Actor = conn.model('Actor', schema);
conn.model('Actor') === Actor; // true
conn.model('Actor', schema) === Actor; // true, same schema
conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name
// This throws an `OverwriteModelError` because the schema is different.
conn.model('Actor', new Schema({ name: String }));
When no collection
argument is passed, Mongoose uses the model name. If you don’t like this behavior, either pass a collection name, use mongoose.pluralize()
, or set your schemas collection name option.
Example:
const schema = new Schema({ name: String }, { collection: 'actor' });
// or
schema.set('collection', 'actor');
// or
const collectionName = 'actor'
const M = mongoose.model('Actor', schema, collectionName)