,

Creating a GET Request with Node, Express, and MongoDB: Part 2 of RESTFUL API and CRUD Operation

Posted by

How to create GET request with Node, Express, and MongoDB | RESTFUL API | CRUD Operation | PART 2

How to create GET request with Node, Express, and MongoDB

In the previous article, we learned how to set up a basic RESTFUL API with Node, Express, and MongoDB to perform CRUD operations. In this article, we will focus on creating a GET request to fetch data from our MongoDB database.

Setting up the GET route

First, let’s define the route for our GET request in our Express application. We can do this using the following code:

app.get('/api/data', (req, res) => {
  // Logic to fetch data from MongoDB
});

In the above code, we have created a GET route with the path ‘/api/data’. When a GET request is made to this route, the callback function will be executed. Inside this function, we will write the logic to fetch data from our MongoDB database.

Fetching data from MongoDB

To fetch data from our MongoDB database, we can use the mongoose library to interact with our database. We can define a mongoose model for our data and then use the find() method to retrieve the data. Here’s an example of how we can do this:

const Data = require('./models/data');

app.get('/api/data', (req, res) => {
  Data.find({}, (err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(200).send(data);
    }
  });
});

In the above code, we first require the mongoose model for our data and then use the find() method to retrieve all the data from the database. If there is an error, we send a 500 status code along with the error message. If the retrieval is successful, we send a 200 status code along with the retrieved data.

Testing the GET request

With the GET route set up and the logic to fetch data in place, we can now test our GET request using a tool like Postman. We can make a GET request to our ‘/api/data’ route and see the retrieved data in the response.

By following the above steps, we have successfully created a GET request to fetch data from our MongoDB database using Node, Express, and MongoDB. In the next article, we will look at creating the POST and PUT requests to create and update data in our database.