Develop Node.js Application with MongoDB and Mongoose

In this lesson , I am going to explain how you can build the Node.js app using the MongoDB and NPM package Mongoose
First be sure you have MongoDB and Node.js installed

What is Mongoose?
It is object modeling package. It is same like ORM (Object Relation Mapping) what you find in other languages for Relational Databases access
With Mongoose you can do CRUD operations simply and easily

First thing you have to do is, installing the Mongoose
In your terminal

After installing the Mongoose package, you can connect to database using following two lines in your index.js file

So now, we have connected to database
Lets create a model for our collection

Defining a Model

Before creating the model, I am going to create a Schema using mongoose.Schema. This model maps with the document in collection

This is the Schema for the product. This Schema just defines the attributes in your document

The permitted SchemaTypes are


When your schema is ready you can create your model now

Create Document

Now lets see how we create new product and save it

Code explanation

  • Line 14: New product is created using the model we created
  • Line 25: Save the product using but-in save() of the Mongoose

Read Document

You can get all products, only one product, product by id and you can specify the query to get set of products. We will see how we are going to achieve it

Find all products

You will get following output in terminal

Find one product
To find one product, you have to specify the product attribute so that Mongoose can locate it

Terminal Output

Find product by Id

Find product by querying
You can find product by making query. MongoDB has good query syntax. You can refer it for more details
In this example I am going to find products which unit prices are greater than 1.25

Terminal Output

Update Document

There are several ways to do update document with Mongoose
First you can get the object and then update the attributes and finally save it. You can use findById() or findOne() to get the product object.
Other method is using the findOneAndUpdate()
Third one is findByIdAndUpdate()
We will how these methods one by one

Find the product first, then update

You can use findById() to get the product

Using findOneAndUpdate()

Using findByIdAndUpdate()

Those are the several method of updating the document. You can use the correct one according your requirements

Delete Document

To delete the document first you have to find it. There are several methods to delete document. It is same like what you learned in update document

Find the product first, then delete

Using findOneAndRemove()

Using findByIdAndRemove()

I hope that you have good understanding to work with Mongoose and Node.js to build your application now