Table of contents
1.
Introduction
2.
First model compilation
3.
Constructing documents
4.
Querying
5.
Deleting
6.
Updating
7.
Change Streams
8.
 
9.
FAQs
10.
Key takeaways
Last Updated: Aug 13, 2025

Mongoose models

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The fancy constructors which are compiled from schema definitions are referred to as models. Documents are the instances of a model. The documents can be created and read very easily from the underlying MongoDB database. 

 

First model compilation

On calling mongoose.model(), a model gets compiled by the mongoose. 

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

 

The first argument signifies the name of the collection of your model as a singular form. The Mongoose automatically searches the lowercase and plural version of the model name. This, for the above example, the model helper signifies the helper collection of the model.In the code, the .model() function is creating copy of schema.

 

Constructing documents

As we have already read above that the instances of a model refer to a document. Its creation and saving for later use in the database is very easy.

 

const Tank = mongoose.model('Tank', yourSchema);

const small = new Tank({ size: 'small' });
small.save(function (err) {
  if (err) return handleError(err);
  // saved!
});
// or

Tank.create({ size: 'small' }, function (err, small) {
  if (err) return handleError(err);
  // saved!
});

// or, for inserting large batches of documents
Tank.insertMany([{ size: 'small' }], function(err) {
});

 

Until any connection of the model is open, we cannot create/ remove any tanks. There exist some of the other interconnected connections. When we are using mongoose.model(), our model will also be using the default mongoose connection.

 

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

 

For creating any custom connection, prefer using the connection’s model.

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

 

Querying

The document searching in Mongoose is very easy. Rich query syntaxes of MongoDB is supported. The documents can be backtracked by find, findById, findOne or where static methods.

 

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

 

Deleting

The deletion is performed by deleteOne() and deleteMany()functions. These function are used for removing all documents matching with the given filter.

 

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

 

Updating

Every model consists of its own modifying methods in the database without returning them to the application.

 

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

 

Change Streams

It provides a way to isten to all the insert and update going through the MongoDB database. These streams won’t work until and unless we are connected to the MongoDb replica set.

 

async function run() {
  // Create a new mongoose model
  const personSchema = new mongoose.Schema({
    name: String
  });
  const Person = mongoose.model('Person', personSchema);

  // Create a change stream. The 'change' event gets emitted when there's a
  // change in the database
  Person.watch().
    on('change', data => console.log(new Date(), data));

  // Insert a doc, will trigger the change stream handler above
  console.log(new Date(), 'Inserting doc');
  await Person.create({ name: 'Axl Rose' });
}

 

 

See More, PHP For Loop

FAQs

  1. Define a schema?
    In Mongoose, the schema refers to the representation of a particular document, either partially or completely. In other ways, the way of expressing indexes, properties, values as well as constraints is known as schema. 
     
  2. Which is better to use MongoDB or mongoose?
    As such there is no benefit, both have its advantages based on different applications it is used for. For multi tenant application, mongoDB native driver is a good choice. Whereas mongoose as an ORM(Object Relational Mapping) is a better option for newbies.

 

Key takeaways

This article covers the introduction of Mongoose models, then we have seen the first model compilation, constructing documents, querying, deleting, updating, and finally how we can change streams.

Keeping the theoretical knowledge at our fingertips helps us get about half the work done. To gain complete understanding, practice is a must. To achieve thorough knowledge, visit our page.

 

Live masterclass