In this article, we are going to learn about one of the most used databases with Node Js,MongoDB.We will learn how to integrate Node JS and MongoDB,make basic APIs for CRUD operations and the pros and cons of using MongoDB as a Database.Now we assume that you have learnt about the basics of Node JS and having it in your systems, if not then go through this article.

This article is split into 2 parts:

Creating CRUD APIs

1- Create

The first operation in our CRUD is to create a new product. Head over to routes.js file and start designing the expected path that the browser would hit.

router.post(‘/create’, (req,res)=>{
let product = new Product(
{
name: req.body.name,
price: req.body.price
}
);
product.save(function (err) {
if (err) {
res.status(400).send(err);
}
res.send(‘Product Created successfully’)
})
});

What this does is it simply creates a new product using the data coming from a POST request and saves it to our database.Last step would testing that we can easily create a new product. Let’s open Postman and send a POST request to the following url ‘localhost:1234/products/create’ and specify the POST data as name: Chocolate and price: 50 as a test example. Also make sure that you choose raw then json format in the Body tab in Postman as specified in the image below and write the product details in json format as shown in image and then click on the send button and will see the same output as shown here.

To verify this download Robo3T which is an IDE for database and shows how data is stored and check there,you will see this product added in database as shown below.

We can see above that a new collection was created named ‘products’ and has one document.

2- READ

The second operation in our CRUD is to read a product by its unique id. Head over to routes.js file and start designing the expected path that the browser would hit.

What the function does is it simply reads an existing product from the product id being sent in the request params.Now let’s head to Postman and try-out our new endpoint. Call the following url ‘localhost:3000/products/PRODUCT_ID’.PRODUCT_ID is the id of the object we just created in the previous endpoint. You should get this from your database and it will be different from mine for sure.

We got a response containing all the info of that specific product. You can see that it is called chocolate and it’s price is 50.

3-Update

The third operation in our CRUD is to update a product with the help of its unique id. Head over to routes.js file and start designing the expected path that the browser would hit.

router.put(‘/update/:id’, (req,res)=>{
Product.findByIdAndUpdate(req.params.id, {$set: req.body}, function (err, product) {
if (err) res.status(400).send(err);
res.send(‘Product updated.’);
});
});

What the function does is it simply finds an existing product using its id that was sent in the params.Now let’s head to Postman and try-out our new endpoint. Call the following URL ‘localhost:3000/products/update/PRODUCT_ID’ PRODUCT_ID is the id of the object we’ve created in the previous endpoint. You should get this from your database and it will be different from mine for sure.

And after hitting this route the price of the product will be changed to 100 which you can verify either by hitting the read route or by checking into the database itself.

Product in database after hitting update route.

4- Delete

The last operation in our CRUD is to delete a product with the help of its unique id. Head over to routes.js file and start designing the expected path that the browser would hit.

router.delete(‘/delete/:id’, (req,res)=>{
Product.findByIdAndRemove(req.params.id, function (err) {
if (err) res.status(400).send(err);
res.send(‘Deleted successfully!’);
})
});

What the function does is it simply deletes an existing product with the help of its unique id.Now let’s head to Postman and try-out our new endpoint. Call the following URL ‘localhost:3000/products/delete/PRODUCT_ID’. PRODUCT_ID is the id of the object we’ve created in the previous endpoint. You should get this from your database and it will be different from mine for sure.

After successfully hitting this route you can check your database in your IDE,that record no longer exists.

HURRAY! And this completes our CRUD operations implemented through APIs using Mongodb as database.

Pros of MongoDB

  • MongoDB is a schema-less database that means we can have any type of data in a separate document. This thing gives us flexibility and freedom to store data of different types.
  • We can store a large data by distributing it to several servers connected to the application. If a server cannot handle such a  big data then there will be no failure condition. The term we can use here is “auto-sharding”.
  • MongoDB is a document-oriented database. It is easy to access documents by indexing. Hence, it provides fast query response. The speed of MongoDB is 100 times faster than the relational database.
  • Performance is very high due to availability of various inbuilt tools..
  • A great advantage of MongoDB is that it is a horizontally scalable database. 
  • It is easier to setup MongoDB. It also provides JavaScript client for queries.
  • MongoDB Inc. provides professional support to its clients. If there is any problem, you can directly reach MongoDB client support system.

Cons of MongoDB

  • MongoDB stores key names for each value pairs. Also, due to no functionality of joins, there is data redundancy. This results in increasing unnecessary usage of memory.
  • One cannot have a document size more than 16MB.
  • MongoDB doesn’t support joins like a relational database. Yet one can use joins functionality by adding by coding it manually. But it may slow execution and affect performance.
  • You cannot perform nesting of documents for more than 100 levels.


That’s all I have and thanks a lot for reading. Please let me know if any corrections/suggestions. Please do share and comments if you like the post. Thanks in advance… 😉


Thanks Yash Kesarvani for helping us to grow day by day. He is expert in Node Js and loves to solve competitive programming.

Categories: Miscellaneous

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert