Connection.prototype.model()

Parameters
  • name «String|Function» the model name or class extending Model

  • [schema] «Schema» a schema. necessary when defining a model

  • [collection] «String» name of mongodb collection (optional) if not given it will be induced from model name

  • [options] «Object»

  • [options.overwriteModels=false] «Boolean» If true, overwrite existing models with the same name to avoid OverwriteModelError

Returns:
  • «Model» The compiled model

Defines or retrieves a model.

  1. const mongoose = require('mongoose');
  2. const db = mongoose.createConnection(..);
  3. db.model('Venue', new Schema(..));
  4. const Ticket = db.model('Ticket', new Schema(..));
  5. const Venue = db.model('Venue');

When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don’t like this behavior, either pass a collection name 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 = conn.model('Actor', schema, collectionName)