You are currently viewing NodeJS, Express, Mongoose and MongoDB RESTful Web Service – GET Request

NodeJS, Express, Mongoose and MongoDB RESTful Web Service – GET Request

Hey in this article, we will discuss how to make HTTP GET requests using NodeJS and Express. In the previous post, we discussed the HTTP POST request, where we saved the data to the database. So we will use the same example which is blogging application, we will make HTTP GET request to retrieve the list of blogs from the MongoDB database. So let’s begin…




Retrieve all the records from the database


So in our previous example, we have already created a separate router for Blog model, let’s open routers/blog.js file and add the following code

router.get('/blogs', (req, res) => {
    Blog.find({}).then((blogs) => {
        res.send(blogs);
    }).catch((error) => {
        res.status(500).send(error);
    })
})

here we will be calling the mongoose find() method on Blog model, and if you look inside the find() the { } curly braces, this clearly says that we do not have any filter/criteria and retrieve all the records from the database.

Retrieve a single record from the database based on Id


So in order make retrieve a single record we will use mongoose findById() on the Blog model, as the name suggests this method will find the record based on the id which means we need to supply an id as a parameter to this method. Open routers/blog.js and add the following code.




router.get('/blogs/:id', (req, res) => {
    Blog.findById(req.params.id).then((blog) => {
        if (!blog) {
            return res.status(404).send();
        }    
        res.send(blog);
    }).catch((error) => {
        res.status(500).send(error);
    })
})

here, :id is the route parameter, using req.params.id we will access the parameter :id which is supplied to the route. So now if the mongoose does not find the record, it will not throw an error, instead, it will return null. So instead of returning null back to the client application, we will check whether the record exists or not, if it does not exist, then we will set the status code as 404. So with this in place, let’s test our work in postman.

Right now in our database, we have 3 records as shown in the below image

Now let’s test our endpoint GET /blogs, this should return all 3 records

Now let’s test another endpoint GET /blogs/id to get a single record




Now let’s pass an invalid id and test the status code, it should return 404

Alright, you can see the status code which is 404 Not Found, which is indeed correct. Now the rest endpoints are working as we expected. In the next article, let’s discuss how to update one of the records, using the HTTP PATCH request, I will see you in the next post.




Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply