DEV Community

Cover image for Read data from a database with a data model
Cesare Ferrari
Cesare Ferrari

Posted on

Read data from a database with a data model

Calling a database from an Express API

In the previous article we started creating an API that responds with data coming from a data model connected to a database.
We have seen how a data model is an intermediary between the Express server and the database.

The server talks to the data model which in turn talks to the database.
Our data model has a method called find that retrieves an array of objects. find returns a Promise that we have to handle in our server code.

The find method

find doesn't take arguments and just returns a JSON object that contains a list of all the records in our database table.
In our API we need to send these record objects back to the client that made the original request.

First let's see what happens when we call the find method and we actually get a JSON object back, that is, when everything goes well and we are on the so called happy path.

In this case, we handle the operation inside the then() method.

We need to do two things inside then().

First, we return a success response status code (200).
Technically we don't need to do this, the 200 response code is returned by default by Express on success anyway. The reason we do it is to make it very explicit to indicate that this is indeed a successful response.

The second thing we need to do is convert our JSON object into text format.
What comes back from the find method is a JSON object, but what we need to send back over HTTP is plain text, so we take advantage of another method on the response object, the json() method provided by Express.

json() is similar to the send() method we have already seen, but performs an extra step of converting a JSON object into plain text and sending the text back to the client.

server.get('/toys', (req, res) => {
  db.find()
    .then(toys => {
      res.status(200).json(toys)
    })
    .catch()
})

Handling errors

Sometimes, when we make a request to a database we may not get what we are expecting. We must be ready to handle an unexpected situation.

This is when catch() comes in. It takes the error that was generated and sends back a response with a status code of 500, a generic error code which means Internal Server Error.

By the way, you can read all about HTTP status codes at the HTTP Status Code Registry

server.get('/toys', (req, res) => {
  db.find()
    .then(toys => {
      res.status(200).json(toys)
    })
    .catch( err => {
      res.status(500).json({error: err})
    })
})

To better display the error, we also call the json() method so we can send back a stringified JSON object that contains the actual error text, represented by the variable err.

API response

Now we are finally set up to actually respond to the /toys endpoint.
If we send a GET request to localhost:4000/toys, we will actually get something back that looks like a list of toys:

id  1
name  "Sock Monkey"
created_at  "2019-05-09 17:33:19"
updated_at  "2019-05-09 17:33:19"

id  2
name  "Microscope Set"
created_at  "2019-05-09 17:33:19"
updated_at  "2019-05-09 17:33:19"

id  3
name  "Red Ryder BB Gun"
created_at  "2019-05-09 17:33:19"
updated_at  "2019-05-09 17:33:19"

(output formatted for clarity)

And now that we have fulfilled the R part of our CRUD operation (R as in: Read from the database), we will learn how to create a new a record by calling an API endpoint. We'll see how to do this in the next article.


I write daily about web development. If you like this article, feel free to share it with your friends and colleagues.

You can receive articles like this in your inbox by subscribing to my newsletter.

Top comments (0)