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:

  1. const mongoose = require('mongoose');
  2. // define an Actor model with this mongoose instance
  3. const schema = new Schema({ name: String });
  4. mongoose.model('Actor', schema);
  5. // create a new connection
  6. const conn = mongoose.createConnection(..);
  7. // create Actor model
  8. const Actor = conn.model('Actor', schema);
  9. conn.model('Actor') === Actor; // true
  10. conn.model('Actor', schema) === Actor; // true, same schema
  11. conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name
  12. // This throws an `OverwriteModelError` because the schema is different.
  13. 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:

  1. const schema = new Schema({ name: String }, { collection: 'actor' });
  2. // or
  3. schema.set('collection', 'actor');
  4. // or
  5. const collectionName = 'actor'
  6. const M = mongoose.model('Actor', schema, collectionName)