Introduction to Mongoose

Tanay Kumar Deo
Last Updated: May 13, 2022

Introduction

Mongoose is one of the most potent external modules of Node.js. Mongoose is an ODM (Object database Modelling) library that allows us to define objects with a schema that is mapped to a MongoDB document. The mongoose acts as the abstraction layer over MongoDB, just like the Express behaves for the Node.js.

Object Mapping between Node and MongoDB managed via mongoose

 

Mongoose is preferred over other MongoDB drivers because of its several functionalities for creating and working with schemas. This schema defines each item of the data, and the SchemaType, whether a number, string, boolean, date, etc.

Getting Started - NPM Install

 

1. First, create a new folder and initialize the project using the npm init command.

npm init

 

Output
 

2. Now let's install the latest version of mongoose with the npm install mongoose command.

npm install mongoose@5

 

The above command will install the version 5 of the mongoose library. Note that this article will be specific to mongoose V5 and beyond, i.e., we will be referring to version 5 of mongoose.

Database Connection

1. Create a file database.js  under the root project folder.

In the file, add a simple class with a method that connects to the database.

let mongoose = require('mongoose');


// Replace with your DB server

const server = '127.0.0.1:27017'; 


// Replace with your DB name

const database = 'mongoose-demo';     


class Database {

  constructor() {

    this._connect()

  }

  
_connect() {

     mongoose.connect(`mongodb://${server}/${database}`)

       .then(() => {

         console.log('Database connection successful')

       })

       .catch(err => {

         console.error('Database connection error')

       })

  }

}


module.exports = new Database()

 

In the above code require(‘mongoose’)  call creates an instance of the Mongoose class and returns it. We then save our MongoDB connection server and database name as a string in the server and database object, respectively. mongoose.connect() is the minimum need to connect the database with the app. 

Also, Database Class is turned into a Singleton object by returning it in the module.exports statement as we only need one single database connection.

 

2. Now, since we have successfully connected our database connection, let's run the database.js with the following line of code: 

node database.js 

 

Hooray!!! Successfully connected our app with the MongoDB database using mongoose.

 

Output

 

Mongoose Schema vs. Model 

A Mongoose model is a wrapper of the Mongoose schema. A Mongoose schema defines the document's properties, default values, types of data, validators, etc. In contrast, a Mongoose model provides an interface for the database to create, query, update, delete records, and so on.

Creating a Mongoose model primarily consists of three parts:

1. Referencing Mongoose: This is the same as the one we used while connecting our database, which implies that defining schema and model does not require an explicit connection to the database.

let mongoose = require('mongoose');

const { Schema } = mongoose;

 

2. Schema Definition: We define a schema to decide the properties of the object including default values, data types, if required, etc., 

const blogSchema = new Schema({

    // String is shorthand for {type: String}

    title:  String, 

    date: { type: Date, default: Date.now },

    body:   String,

});

 

Here blogSchema defines a few basic properties for a blog. We've defined a property title and body of the String SchemaType, and property date that will be of a Date SchemaType, and its default value is set to Date.now, which provides a current date.

Currently, 8 SchemaTypes are allowed in mongoose:

  • Array
  • Boolean
  • Buffer
  • Date
  • Mixed (A generic/flexible data type)
  • Number
  • ObjectId
  • String

 

3. Creating and Exporting a Model: To use the schema defined, we need to convert blogSchema into a Model we can work with. To do this, we will use the following code: 

// Creating a Model

let blog = mongoose.model('Blog', blogSchema); 


// Exporting the created module

module.exports = Blog 

 

We can use this Blog model to efficiently perform operations like create, read, update, delete, etc., from our database.

Advantages of mongoose:

  1. Validation of the MongoDB database collections can be done very effectively with mongoose.
  2. Implementation of predefined structures on Collections is done quickly.
  3. Mongoose module provides the abstraction layer for reading and defining a query.

Disadvantages of mongoose:

The main disadvantage of mongoose is that the abstraction comes at the cost of performance as compared to the MongoDB driver. MongoDB driver is around 2x faster than the Mongoose.

Companies using mongoose:

Mongoose is a modern library and is widely used in the industry. Reportedly there are more than 183 companies using mongoose in their tech stack. Popular companies using mongoose as their tech stack are Stack, Accenture, Scale, PedidosYa, Wunderflats, Winds, and many more.

Frequently Asked Questions-

Q1. What is node js?

Ans. Node.js is a platform built on Chrome’s V8 JavaScript runtime for building fast and scalable javascript network applications.  

 

Q2. What is MongoDB?

Ans.  MongoDB is a document-oriented NoSQL database mainly used for large-scale and medium-scale data storage.

 

Q3. What is the difference between Mongoose and MongoDB?

Ans. MongoDB is a NoSQL database, while mongoose is a tool used for object modeling for MongoDB.

Mongoose is built on top of the MongoDB driver to provide us with a means to model data easily.

 

Q4. Name some tools that are integrated with mongoose?

Ans. Node.jsMongoDBScaleGridJScrambler, and eXist-db are some of the popular tools that integrate with Mongoose.

Key Takeaways-

In this blog, we learned the basic functionalities offered by mongooses and the advantages of using mongoose. We also discovered how to connect MongoDB with the Node.js app using mongoose. By using mongoose, we can simplify all the processes.

If you want to learn advanced web development, Coding Ninjas has one of the best courses available, which you can find here.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think