Models

Models are fancy constructors compiled from our Schema definitions. Instances of these models represent documents which can be saved and retrieved from our database. All document creation and retrieval from the database is handled by these models.

Compiling your first model

  1. var schema = new mongoose.Schema({ name: 'string', size: 'string' });
  2. var 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 version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database. The .model() function makes a copy of schema. Make sure that you’ve added everything you want to schema before calling .model()!

Constructing documents

Documents are instances of our model. Creating them and saving to the database is easy:

  1. var Tank = mongoose.model('Tank', yourSchema);
  2. var 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. })

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('localhost', 'gettingstarted');

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

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

Querying

Finding documents is easy with Mongoose, which supports the rich query syntax of MongoDB. Documents can be retreived using each models find, findById, findOne, or where static methods.

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

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

Removing

Models have a static remove method available for removing all documents matching conditions.

  1. Tank.remove({ size: 'large' }, function (err) {
  2. if (err) return handleError(err);
  3. // removed!
  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.

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

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.