DEV Community

Cover image for Introduction to Mongoose
Iftakher Hossen
Iftakher Hossen

Posted on

Introduction to Mongoose

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. Mongoose is a JavaScript object-oriented programming library that creates a connection between MongoDB and the Express web application framework.

MongoDB is a schema-less NoSQL document database. It means you can store JSON documents in it, and the structure of these documents can vary as it is not enforced like SQL databases. This is one of the advantages of using NoSQL as it speeds up application development and reduces the complexity of deployments.

Mongoose uses schemas to model the data an application wishes to store and manipulate in MongoDB. This includes features such as type casting, validation, query building, and more.
The schema describes the attributes of the properties (aka fields) the application will manipulate. These attributes include such things as:

  • Data type (e.g. String, Number, etc.).
  • Whether or not it is required or optional.
  • Is it’s value unique, meaning that the database is allowed to contain only one document with that value in that property.

A model is generated from the schema and defines a document the application will operating on. More precisely, a model is a class that defines a document with the properties and behaviors as declared in our schema. All database operations performed on a document using Mongoose must reference a model.

A schema definition can be as simple as the following code snippet:

var userSchema = new mongoose.Schema({
  firstname: String,
  lastname: String,
  createdOn: Date
Enter fullscreen mode Exit fullscreen mode

A document in MongoDB created from this schema would be like the following code snippet:

{ "__v" : 0, "_id" : ObjectId("51412597e8e6d3e35c000001"),"createdOn" : ISODate("2022-03-04T08:29:19.866Z"),"firstname" : "Iftakher", " lastname " : "Hossen" }
Enter fullscreen mode Exit fullscreen mode

What is Mongoose good for?

Mongoose is primarily useful when you want to interact with structured data in MongoDB. It allows you to define a schema for your data, so that you can interact with your MongoDB data in a structured and repeatable way. Mongoose helps with many common MongoDB tasks, and removes some of levels of complexity from the nested callbacks you find yourself getting lost in with the native MongoDB driver. Mongoose also returns the data to you as a JSON object that you can use directly, rather than the JSON string returned by MongoDB.
Mongoose also has a whole suite of helper functions and methods that we'll explore throughout the subsequent chapters of this book.

What Mongoose is not ideally suited for

Mongoose is probably not the answer for you if you are primarily working with the following:

  • Schema-less data
  • Random documents
  • Pure Key-Value pairs

The cornerstones of Mongoose

There are two aspects of Mongoose that we need to introduce you to before going much further:

  • Schemas
  • Models


  • Collections - ‘Collections’ in Mongo are equivalent to tables in relational databases. They can hold multiple JSON documents.

  • Documents - ‘Documents’ are equivalent to records or rows of data in SQL. While a SQL row can reference data in other tables, Mongo documents usually combine that in a document.

  • Fields - ‘Fields’ or attributes are similar to columns in a SQL table.

  • Schema - While Mongo is schema-less, SQL defines a schema via the table definition. A Mongoose ‘schema’ is a document data structure (or shape of the document) that is enforced via the application layer.

  • Models - ‘Models’ are higher-order constructors that take a schema and create an instance of a document equivalent to records in a relational database.

The three main advantages of using Mongoose versus native MongoDB are:

  • MongooseJS provides an abstraction layer on top of MongoDB that eliminates the need to use named collections.
  • Models in Mongoose perform the bulk of the work of establishing up default values for document properties and validating data.
  • Functions may be attached to Models in MongooseJS. This allows for seamless incorporation of new functionality.
  • Queries use function chaining rather than embedded mnemonics which result in code that is more flexible and readable, therefore more maintainable as well.

The net result of these is the simplification of database access from applications. The main disadvantage of Mongoose is that abstraction comes at the cost of performance compared to that of native MongoDB.

Mongoose Schema

As we saw earlier, a schema is fundamentally describing the data construct of a document. This schema defines the name of each item of data, and the type of data, whether it is a string, number, date, Boolean, and so on.

var userSchema = new mongoose.Schema({
  name: String,
  email: String,
  createdOn: Date,
  verified: Boolean
Enter fullscreen mode Exit fullscreen mode

In most scenarios you would have one schema for each collection within the database. Schemas are a powerful aspect of Mongoose, which can also be extended with helper functions and additional methods. But we'll describe more about that in a later chapter.

Mongoose models

A model is a compiled version of the schema. One instance of the model will map to one document in the database. Creating a User instance based on the schema userSchema is a one line task:

const User = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode

It is the model that handles the reading, creating, updating, and deleting of documents.

Visit Mongoose.js official site to read the documentation and know more in detail.

In this tutorial, I try to clarify What is Mongoose and it's features. If I made any mistakes pardon me! And I'd love to hear from you If you have any suggestions for me. Thank you for reading this blog!

Find me on Github and Portfolio or Send a Mail

Follow for more blogs!

Discussion (0)