In this blog, we are going to learn how to perform CRUD (Create, Read, Update and Delete) operations with the help of Rest API using Node.js, MongoDB as our database, and Expess.
REST
In simple terms, REST stands for Representational State Transfer. It is an architectural style design for distributed hypermedia, or an Application Programming Interface (API). In REST, we use various standard HTTP
methods like GET
, POST
, PUT
and DELETE
to perform any CRUD
operation on resource.
Resource
In REST
, everything is Resource
. A resource can be an image, document, a temporary service, a collection of other resource, and any other object. Each resource has resource identifier to identify it.
HTTP Methods for CRUD
As per REST
guidelines, we should use only HTTP
methods to perform CRUD
operation on any resource. In this blog, we are going to use 4 HTTP methods like GET
, POST
, PUT
and DELETE
to make our REST
API.
Let’s have a brief introduction of each http method here.
- HTTP GET
The HTTP GET
is used to Read
or Retrieve
any resource. It returns the XML or JSON data with HTTP status code of 200. GET method is considered as safe, because we are just getting or reading the resource data, not doing any changes in the resource data.
- HTTP POST
The HTTP POST
is used to Create
a new resource. On successful creation of resource, it will return HTTP status code of 201, a Location header with a link to the newly created resource.
- HTTP PUT
The HTTP PUT
is used to Update
any existing resource. On successful, it will return HTTP status code of 200.
- HTTP DELETE
The HTTP DELETE
, as the name suggests, is used to Delete
any existing resource. On successful, it will return HTTP status code of 200.
HTTP Methods | CRUD | Status Code |
GET | Read | 200 (OK), 404 (Not Found) |
POST | Create | 201 (OK), 404 (Not Found), |
PUT | Update | 200 (OK), 204 (No Content), 404 (Not Found) |
DELETE | Delete | 200 (OK), 404 (Not Found) |
Let’s move forward into the details of other pieces of creating our REST API.
Express.js
We are going to use Express.js or simply Express. It is a web application framework for Node.js. It has been released as free and open source software. You can create web application and APIs using Express. It has support for routing, middleware, view system etc.
Mongoose
Mongoose is Object Document Mapping or ODM tool for Node.js and MongoDB. Mongoose provide a straight-forward, schema based solution to model to your application data. It includes built-in type casting, validation, query building, business logic hooks and many more.
Prerequisites
You must have Node.js and MongoDB installed on your machine. Click the below links, if you don’t have any one of them.
For MongoDB, I am using mLab free account for online MongoDB database. You can try this one as well, instead of installing on your local machine.
Database-as-a-Service for MongoDB
Install Postman – Google Chrome for testing purpose.
After setting up prerequisites, let move forward to build our application.
Application Introduction
In our application, we are going to create a product based application. We will use REST APIs to create, update, get and delete the product. Let’s go to create our application.
1. Create package.json
Let’s create a folder, and start with creating package.json
file first. Use this command in your terminal window.
npm init
package.json
If you notice line 5, we have defined server.js
as our main entry point.
2. Install Packages
Let’s install all the express
, mongoose
and body-parser
package dependencies in our app.
npm install express body-parser mongoose –save
Once these packages installed successfully, our package.json
file will be updated automatically. Our latest file will be like this.
package.json
Notice dependencies
section of our file, all these packages are mentioned there.
3. Creating Our Server
Let’s create a server.js
file in the root directory of the application.
server.js
Let’s briefly review our above code. First of all, we imported the required dependencies in our server.js file.
body-parser
It is Node.js body parser middleware. It parse the incoming request bodies in a middleware before your handlers, available under the req.body
property.
Learn more about bodyParser.urlencoded([options])
Learn more about bodyParser.json([options])
Then, we define a default route using GET Http method. By default, it will return our message on default url.
Finally, we are going to listen all incoming requests on port 3000.
4. Run the server
Once everything is all set, let’s wake up our server by running this command in our terminal window.
node server.js
Server is listening on port 3000
5. Create Configuration file
Let’s create a config file in our app, where we can define various constants like dbconnection or port number instead of hard-coded it everywhere. So, create a config.js
file in your app folder.
config.js
So, here I mentioned two constants in config.js
file.
- url: Our MongodB connection url.
- serverport: Our listening server port.
6. Connecting to Database
Let’s connect with our MongoDb database. Add these lines of codes in server.js
file after the app.use(bodyParser.json());
Also, we are going to replace our hard-coded server port with our config constant in server.js file
Here, you can see, we are now using config.serverport
in app.listen().
Now, run again the server using this command.
node server.js
Server is listening on port 3000
Successfully connected to the database
7. Creating Product Model
Let’s create a product
model in our app folder in order to save the data in our db. Create a product.model.js
file in your app.
product.model.js
Here, we have defined our ProductSchema
with following properties. Along with this, we also set timestamps
property to true
. This property will add two fields automatically to schema. These fields are : createdAt
and updatedAt
in your schema.
8. Creating our Controller’s functions
We are going to write all functions related to create, retrieve, update and delete products in our controller file. Let’s create a controller file named product.controller.js
in your app folder.
product.controller.js
9. Defining Product API’s Routes
Next step is to create our api routes. Create a product.routes.js
file in your app folder.
product.routes.js
Note: import this route file in our server.js file after these lines. See line 4 in the below code.
10. Enable the CORS
If you try to access your api routes through your client-side app, you might face Access-Control-Allow-Origin
error messages. So, in order to avoid these message, we are also enabling CORS
in our server.js
file.
server.js
So, this will be our final server.js
file.
server.js
This will be our project structure.

Testing our REST APIs
Now, it’s time to test our all REST APIs for CRUD Operation.
- Create Product

I have added few products in the database. See the below screen shot.

- Get All Products

- Get Single Product

- Update Product
Before Update

After Update

- Delete Product

Download
You can download all the project files from GitHub.
Summary
In this blog, we learned about how to create a Node.js RESTful API app. We learned about how to perform CRUD operation on MongoDB database. Also, We learned about how to call our APIs endpoint in POSTMAN, and get the results.
Further Reading
Install Node.js and NPM on hosting server
Update Angular 6 to Angular 7 version
Creating your first app in Angular 7
Please visit How to Download & Install MongoDB on Windows to read more about MongoDB.
The best article on CRUD I’ve ever red
Thank you
The best article on CRUD I’ve ever read
Just what I was looking for really great article! I am really new to UI/frontend/REST but is it a thing in web development world to name things “res”, “req”, “err”. The code that I am looking at work has things named like that.
Thanks again.
Thank you Rakesh
Hey guys,
MongooseError: The
uri
parameter toopenUri()
must be a string, got “undefined”. Make sure the first parameter tomongoose.connect()
ormongoose.createConnection()
is a string.Happend after created config.js when running node server.js.
I got this error . Google results this –> https://stackoverflow.com/questions/51770772/mongoose-connect-first-argument-should-be-string-received-undefined
Cofused and stuck. Any help would be appreciable. Have a nice day
Pingback: itemprop="name">Angular 7 CRUD With Node.JS API - ZeptoBook
The article explains everything in details.
Thanks
Hello sir,
Could you explain what is happening on line 22 in final server.js file where we are requiring product.routes.js file.
I understood that we are requiring routes file, but why are we passing (app) as the parameter and how app is being used in product.routes.js file.
Thank you
Hi Adesh i really appreciate the efforts portrayed in this blog. Your article is comprehensive and very clear making it my go to reference whenever i’m stack and need help in creating Rest Apis. However,I could really appreciate your help in embedding mongoose schemas. I have basic understanding about the workings of mongoose but i can’t find my way through embedding documents. Thanks.
Pingback: itemprop="name">Running GraphQL Server Using Node.JS & Express on Linux Hosting Server - ZeptoBook
Thanks a lot for this tutorial.
I’m not done yet but I wanted to share something I had an issue with and how it was solved as it might be worth mentioning. In part 6 (connecting to db) I was getting the error “MongoParseError: URI malformed, cannot be parsed”. I ended up figuring out it was because I had special characters in the password for my mongodb user. I fixed it by modifying config.js with the layout here https://stackoverflow.com/a/54626342 and then adapting mongoose.connect in server.js to use the auth portion.
Great article
Adesh, Mongoose encapsulates bank functions for findOne, find, insert, update, updateOne, and remove? Is that the idea?
Great and easy explanation, thank you for sharing
Hi sir please why do you used res.send in your controller file.And not res.json({}) ?
super article.Dommage juste qu’il n’ai pas de notion de relation avec d’autres modèles ..
Thank you Adesh for great article. Can you please explain how to add and select a product with variations, aka sizes, colors.
How do I have to update in the product.model.js file the ProductSchema?
size: [ ] & color: [ ] as an empty array?
How about product.controller.js? size: req.body.size & color: req.body.color ?
Thank you
i can’t make the code to work in POST.
my database look like this:
{
“_id”: {
“$oid”: “5ce2b7a390c92e22404ab876”
},
“title”: “No product title”,
“createdAt”: {
“$date”: “2019-05-20T14:20:19.636Z”
},
“updatedAt”: {
“$date”: “2019-05-20T14:20:19.636Z”
},
“__v”: 0
}
i’m not getting any error message.
please help me .image doesn’t show in your article after all changes i run my node server then what i do??
Thanks for the post. But i had a problem with my, during testing with postman i was only getting createat and update at. and nothing was showing for my title, company and price
Thanks for sharing helpful article.