Models

Models are fancy constructors compiled from Schema definitions. An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.

Compiling your first model

When you call mongoose.model() on a schema, Mongoose compiles a model for you.

  1. const schema = new mongoose.Schema({ name: 'string', size: 'string' });
  2. const Tank = mongoose.model('Tank', schema);

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database.

Note: The .model() function makes a copy of schema. Make sure that you’ve added everything you want to schema, including hooks, before calling .model()!

Constructing Documents

An instance of a model is called a document. Creating them and saving to the database is easy.

  1. const Tank = mongoose.model('Tank', yourSchema);
  2. const small = new Tank({ size: 'small' });
  3. small.save(function (err) {
  4. if (err) return handleError(err);
  5. // saved!
  6. });
  7. // or
  8. Tank.create({ size: 'small' }, function (err, small) {
  9. if (err) return handleError(err);
  10. // saved!
  11. });
  12. // or, for inserting large batches of documents
  13. Tank.insertMany([{ size: 'small' }], function(err) {
  14. });

Note that no tanks will be created/removed until the connection your model uses is open. Every model has an associated connection. When you use mongoose.model(), your model will use the default mongoose connection.

  1. mongoose.connect('mongodb://localhost/gettingstarted');

If you create a custom connection, use that connection’s model() function instead.

  1. const connection = mongoose.createConnection('mongodb://localhost:27017/test');
  2. const Tank = connection.model('Tank', yourSchema);

Querying

Finding documents is easy with Mongoose, which supports the rich query syntax of MongoDB. Documents can be retrieved using a model‘s find, findById, findOne, or where static methods.

  1. Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback);

See the chapter on queries for more details on how to use the Query api.

Deleting

Models have static deleteOne() and deleteMany() functions for removing all documents matching the given filter.

  1. Tank.deleteOne({ size: 'large' }, function (err) {
  2. if (err) return handleError(err);
  3. // deleted at most one tank document
  4. });

Updating

Each model has its own update method for modifying documents in the database without returning them to your application. See the API docs for more detail.

  1. Tank.updateOne({ size: 'large' }, { name: 'T-90' }, function(err, res) {
  2. // Updated at most one doc, `res.modifiedCount` contains the number
  3. // of docs that MongoDB updated
  4. });

If you want to update a single document in the db and return it to your application, use findOneAndUpdate instead.

Change Streams

New in MongoDB 3.6.0 and Mongoose 5.0.0

Change streams provide a way for you to listen to all inserts and updates going through your MongoDB database. Note that change streams do not work unless you’re connected to a MongoDB replica set.

  1. async function run() {
  2. // Create a new mongoose model
  3. const personSchema = new mongoose.Schema({
  4. name: String
  5. });
  6. const Person = mongoose.model('Person', personSchema);
  7. // Create a change stream. The 'change' event gets emitted when there's a
  8. // change in the database
  9. Person.watch().
  10. on('change', data => console.log(new Date(), data));
  11. // Insert a doc, will trigger the change stream handler above
  12. console.log(new Date(), 'Inserting doc');
  13. await Person.create({ name: 'Axl Rose' });
  14. }

The output from the above async function will look like what you see below.

  1. 2018-05-11T15:05:35.467Z 'Inserting doc'
  2. 2018-05-11T15:05:35.487Z 'Inserted doc'
  3. 2018-05-11T15:05:35.491Z { _id: { _data: ... },
  4. operationType: 'insert',
  5. fullDocument: { _id: 5af5b13fe526027666c6bf83, name: 'Axl Rose', __v: 0 },
  6. ns: { db: 'test', coll: 'Person' },
  7. documentKey: { _id: 5af5b13fe526027666c6bf83 } }

You can read more about change streams in mongoose in this blog post.

Yet more

The API docs cover many additional methods available like count, mapReduce, aggregate, and more.

Next Up

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