To make RESTful CRUD API’s with Node.js, Express and MongoDB

Sarthak Mittal
10 min readJul 5, 2020

Hello guys, so here we are going to make REST-ful API’s popularly known as REST API’s for CRUD operations (Create-Read-Update-Delete) using node, express and MongoDB from scratch. It will give you a very amazing experience as we are going to directly interact with the back-end development used in any site, We will use node.js as our language for developing the server.

So first of all I will mention some requirements required for developing these API’s, For this you have node installed in your system and also MongoDB as we are using MongoDB as our database. So first of all we will learn what is basically node, express and MongoDB.

Node.js : Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Express : Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications.

MongoDB : MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document.

Now one question may be arise in your mind that what are REST API’s and what’s the benefit of developing them?

So here is the answer:

REST suggests to create an object of the data requested by the client and send the values of the object in response to the user. For example, if the user is requesting for a movie in Bangalore at a certain place and time, then you can create an object on the server-side.

So, over here, you have an object and you are sending the state of an object. This is why REST is known as Representational State Transfer.

The REST API creates an object, and thereafter sends the values of an object in response to the client.

So, that’s all with the theory part, now we will proceed to developing such awesome API’s, for this node.js must installed on your system in correspondence with MongoDB and postman(where we will call these api’s)

To install node.js please refer here

To instal MongoDb please refer here and you will need robo3T if you want to make the database locally, I am using robo3T for downloading refer here

Now the last download is of postman, the platform where we will call all our API’s, to download this refer here

One thing keep in mind that on installing these software will ask you to set their path please allow them to proper functioning

So let’s our node-version for this type command in your command prompt

node -v

node-version

Now node.js is working so let’s start coding, for this open any of your editor liken visual studio code |sublime text or any other

In the terminal write

npm init

Then your app will be initialized installing all basic dependencies, here you have to just pass some details if you want otherwise no need but in the package name enter crud or any single word, command prompt will look like this

So now we will going to install some dependencies that will require in developing our api’s like express,body-parser and mongoose, So in terminal write

npm install express body-parser mongoose

So, one file will be created in your app folder named package.json that will contain all the information regarding your app, it will look like this

package.json

Now we will make our app directory all the folders and files so create folders and js files in them stated below

Here index.js file is the main file from where our app will configure, app folder consist 3 folders, controllers container our all API’s function which we will define, models folder consist file named model.js there we will define schema of our model, in our case I am considering a Note model on which we will perform our all operations, and routes.js in routes folder contains all the routes, and database folder contains our url of our database.

So let’s define our basic server

Now for running this write in your terminal

node index.js

Now instead of writing again and again node index.js everytime you do some changes, we will install nodemon which which automatically restarts the server, so for this write in terminal

npm install nodemon

After installing write nodemon in the terminal and you will see server is running

Now, Its the time to connect to the database, for this open file myurl.js in database folder and copy below code in it, it contains the url of our database

Now add some code to your index.js file to include database as we are importing url from database/myurl.js, your index.js will look like this

Here I have imported myurl.js file as well as connect to the database, so after adding this see your terminal you will find this

Now we have developed our basic server along with connection with database, now it’s the time to define our database model, so in models.js paste this code which defines the structure of our schema

It’s a basic schema which include only three fields i.e. title of note, author, and content in that note, I have also defined timestamp property so that the time at which the current note has created or updated must be with us.

Now, we will define all the routes means the api urls in routes.js

Here, I have 5 routes, first one to create any note, second one to see all the notes created till now, third one finding a particular note, then 2 routes for updation and deletion, in this file we are importing functions from the file controller.js and we will export our app defined in this file to index.js file so that our app will work,I have defined all these routes and functions in different folders to increase your understanding that how it all works.

Here, url for any api is localhost:300(as our app is listening on port 3000) along with the content written in single commas in app.get,app.post functions

So, api for creating a note would be

localhost:3000/api/create

So lets define our controller.js file

First of all, I will create create function for creating any note, in controller,js you have to import note schema

Here, first of all we will check that none of the field can’t be empty, after that we will make a new object that will store content of this note that need to be created, now we will check whether any note with same title exists or not, If yes then we will return the json object stating some message and error code 400, if title doesn’t exists then we will save this note and return the saved note with the note id in our database with status code 201(which means created)

Our second task is to create function for getting all the notes created till now, for this add this code to your file

Here we just call mongo function of find which will find all the notes created till now and return all the notes with status code 200(means done)

If we have to search any particular note for this we will define new function that will use in findone route

Here we will first extract id from the url that i will tell you afterwards how to embeed your id in url, then we will use function findById and pass our id, if no note is found with given id then we will direcltly pass message stating that no note has been found with 404 not found code but if we have found we will return it

Next step is to write function for updating any note, here user has to give the id of the note whose data he wanted to be updated, so code for that function is below

Here first we have to see the content shouldn’t be empty, then simply extract id and then use function to search on behave of id and then update with reference to the new data that has been provided by user, here if no note has been found with given id then we will directly return with message with 404 not found code else the note has been updated and we will return the updated note to user.

Now the final function is to delete the note with given id for this function is so simple

Here simply we have to use the function of findByIdAndDelete and pass the id and then if no note has been found with such id then again just like before we have to pass the message along with 404 not found code otherwise the particular note has been deleted so we will pass the info to the user that deletion has been done successfully

Now we have to include our app from routes.js in index.js so we have add just one line in index.js which is

So our index.js will look like this

So, we have done with the coding, now it’s the time for testing our API’s, for this I will be using postman. In postman open new url box and first of all we have to create a note then we will perform all our operations on that, so to create a note we have to pass the fields so open body and set json as shown below

Now add api in the gray box, for creating note it is

localhost:3000/api/create

We will add all the fields like title, author and content as shown below

One thing keep in mind that check for the request type and if it is GET change it to POST as we are creating some thing, So finally we will press send button for creating the user and this will be the output

Here we have got output with the generated id.

So lets create one more note but remember if you pass same title then error message will show

Now, I have created 2 notes, so i will call GET request for finding all the notes, for this you don’t need to pass anything in the body, just write the url as

localhost:3000/api/notes

The output will be like this

After this we will find any note with id, so copy the id of any of the note given below and call the api

localhost:3000/api/note/<your id>

And the output will be like this

Our next operation is to update so for this, again we have to pass id means appending the id in the url like this

localhost:3000/api/update/<your id>

Then again write the updated of data of note in body and one thing more change the request type from GET to PUT(as it’s a put request to update anything). Output will be

So our note is updated, to make sure that update operation done well we will search the note with it’s id using find api

Yes, it got updated….

So, this is our final operation of deleting any note for this we will call the delete api and append our id in its url

localhost:3000/api/delete/<your id>

We have got confirmation from server side that note associated with this id got deleted, to verify this call the find api and see

No note has been found with this id, means we have deleted this note successfully.

So that’s all with this….

Conclusion

In this blog we have learnt how to create RESTful CRUD API’s usingnode.js , express and MongoDB. I hope you all enjoyed this………

For more information regarding this CRUD api’s and seeing its code and to learn many node.js functionalities please refer to my git repository

Thankyou-)

Have a nice day!!!!

--

--

Sarthak Mittal

Upcoming SDE @Amazon India, Former UI dev Intern @Siemens India, SIH’20, NIT KKR’22