Rest api node js express mongodb
In this article, we'll build a RESTful API using Node, Express, and MongoDB. We will create endpoints for creating data, reading data, updating data, and deleting data (basic CRUD operations). Show
But before we get started, make sure you have Node installed in your system. If not, go to https://nodejs.org/en/download/ to download and install it. Let's do the basic setup firstIn an empty folder, run the following command:
This command will ask you for various details, such as the name of your project, the author, the repository, and more. Then it will generate a package.json file in that folder. Package.json file
This Package.json file will contain all the scripts, like how to run the app, or how to test the app, as well as all the dependencies. We need to install a few dependencies now.
Here,
So go ahead and install them. After they have finished installing, create one file named index.js. This will be the entry point for our application. And in this file, let's add ExpressandMongoose, and run the file.
Now, transfer the contents of Expressinto a new constant called app.
Now, let's listen the changes of this file on port 3000.
Now, the server is set on Port 3000. Let's write the script to start our server. We have also added the app.use. Inside that, we have a code snippet that allows us to accept the data in JSON format. In the package.json file, add a script which says the following:
This means that we can start our server using npm start, and it will run using theNodemonpackage that we previously installed. Type npm start in the terminal, and we will see the following output in the terminal: How to Configure the MongoDB DatabaseNow, let's configure the mongoDB Database. Head over to https://account.mongodb.com/account/login and create your account, or sign in if you already have one. After signing in, we have to create a database. So, create a Free Shared Cluster. It will ask you the username and the password, so fill those in. Then, add your IP Address. Click Finish and Close. It will take some time for our cluster to finish, so let's wait. Meanwhile, create a file called .env in the project folder. And in the Cluster Home page, click the connect button. The following window will appear: Click MongoDB Compass, and it will return the following string. Also, download and install MongoDB Compass. Add your username and password to this string that you have used before. The final connecting string will look something like this:
Here, nishant is the username, followed by the password, and last is the database name. So, paste this string into the .env file.
Now in MongoDB Compass, add this string as well. Then, click Connect. Here, we will get two Databases which are default. A third one will be automatically created later. Now, let's import the contents of our .env file in the script file, index.js.
Here, we are storing the string into a variable called mongoString. Now, let's connect the database to our server using Mongoose.
Now, we have to throw a success or an error message depending on whether our database connection is successful or fails.
Here, database.on means it will connect to the database, and throws any error if the connection fails. And database.once means it will run only one time. If it is successful, it will show a message that says Database Connected. Here is the whole code up to this point:
How to Create our Routes for the EndpointsCreate a folder called routes, and inside make a file called routes.js. Import this file into our main script file, index.js.
Also, let's use this routes file.
Here, this app.use takes two things. One is the base endpoint, and the other is the contents of the routes. Now, all our endpoints will start from '/api'. We will get an error because we don't have anything inside the routes file. So, let's add them.
Here, we are using Router from Express, and we are exporting it too using module.exports. And now, our app will work fine. How to Write our EndpointsNow, let's write our endpoints here in this routes file. We will have five routes for the following actions:
So, let's create the routes for these actions:
We have five methods that use the REST Methods of Post, Get, Patch, and Delete. This router is taking the route as the first parameter. Then in the second parameter it's taking a callback. In the callback, we have a res and a req. res means response, and req means request. We use res for sending responses to our client, like Postman, or any front-end client. And we use req for receiving requests from a client app like Postman, or any front-end client. Then in the callback body, we are printing a message that says the respective API message. Save this, and open Postman to check the endpoints. Download Postman if you don't have it. It is an amazing tool to test API endpoints. Add this address in the address bar, then click Send, or press enter. We will get this message in the body of Postman, because we are simply sending a Message using res.send. Now, let's take a response from a client app. Let's simply print an ID. We have to change the getOne function first. We are getting the ID using req.params.id, and then sending it to the client app using res.send.
Add this endpoint in the address bar. Here, we are using getOne Endpoint, followed by the ID. Then, click Send. We will get the ID in the response body in Postman. How to Create the ModelNow, let's create a Model that will define our database structure. Create a folder called model and inside, a file called model.js.
Here, we have a schema that defines our database structure. It has a name and an age property. Both fields have types and both are required. Then, we are simply exporting the schema model. Now, import this model inside the routes.js file.
How to Post Data to the DatabaseLet's create the data body to post using the model we just created.
Our name and age is accepting the name and age from req body. We get this data from the client app such as Postman, or any frontend client like React or Angular. We will also create a try-catch block to handle success messages and errors.
In the try block, we are saving the data using data.save().Then, we are storing the data in a const called dataToSave. We are also sending the success message with the data in the response body. And in the catch block, we are receiving any errors if we get any.
Now, let's add some data from Postman. But before that, this function needs to be asynchronous to work. So, we will use async-await.
If we add the data in the body and click Send, we will get the following: It's also generating a unique ID. Open the MongoDB Compass app, and you will see the database and this record you just created: How to Get All the DataGetting data is simple too. Just a few lines of code:
Here, we are using the Model.find method to fetch all the data from the database. Then, we are returning it back in JSON format. If we have an error, we will get that too. If we call this endpoint in Postman, we will get an array of objects in the Postman body. How to Get Data Based on the IDThis one is also simple. We just have to pass the ID of the document, which is req.params.id, in a method called findById.
If we click Send, we will get the data based on the ID. How to Update and Delete Data Based on the IDFirst, let's target the update method using the patch method.
Here we have three parameters that we are passing in the findByIdAndUpdate method, which we use to find a document by ID and update it. The req.params.id is the const id, updatedData which contains the req.body, and the options, which specifies whether to return the updated data in the body or not. Let's test it out now. Just paste the ID of a specific document, and click Send. Change the endpoints as well. We are updating using one ID, and it's getting updated. Deleting is also simple. Let's implement it:
We are getting the ID here, and then we are using Model.findByIdAndDelete to delete that field, while passing the id. We are storing the updated data in a const data. In the response, we will get the message that that document with the specific name has been deleted. If we test this, we will get the following: So, all five methods are done. We can Post data and Get all the data (based on ID too). We can also Update them and Delete them. Thank you for reading!In this article, you learned all about how to design and develop a RESTful API using Node, Express, and MongoDB. Now you can use these endpoints to build a Full-Stack application, with Vanilla JavaScript, React, Angular, Next, or Vue.js. You can also check out my video on the same topic, RESTful APIs - Build a RESTful API using Node, Express, and MongoDB Feel free to download the code from Github and experiment. Happy Learning. Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started How do I create a REST API in node js with MongoDB?Steps to Build a REST API using Node Express MongoDB. Step 1: Connecting to MongoDB Atlas.. Step 2: Adding REST API CRUD Routes.. Step 3: Setting Up the Front-End.. Step 4: Testing the Application.. Does MongoDB have a REST API?MongoDB REST API is simple to set up and allows you to store and retrieve documents, making it great for Unstructured Data. Using Express JS as the backend web server with MongoDB as the document store is a common way of implementing the MongoDB REST API strategy.
How does node Express Connect to MongoDB?Connect to a cluster in MongoDB cloud. Connection code. Provide the MongoDB URI of your cluster to mongoose.connect() ( refer to this article for creating a free-tier cluster for MongoDB in the cloud) mongoose.connect( ... . Define a schema. Let's create a schema for a new collection. ... . Define the model.. Can we create REST API using node JS?Node. js can be used to create a variety of applications, including Command-Line Applications, Web Applications, Real-time Chat Applications, REST API Servers, and so on.
|