,

Node.js and Express.js Series: Chapter 20 – Retrieving Records from the Database

Posted by






Node.js & Express.js Series | Chapter 20 | Fetch records from the database

Node.js & Express.js Series | Chapter 20 | Fetch records from the database

In this chapter, we will learn how to fetch records from the database using Node.js and Express.js.

First, let’s create a new route in our Express.js application to handle the request to fetch records from the database:

    
const express = require('express');
const app = express();

app.get('/records', (req, res) => {
    // Code to fetch records from the database
});
    

Next, we need to connect to the database and fetch the records. We will use a database client library such as Mongoose for MongoDB or Sequelize for SQL databases:

    
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/records', { useNewUrlParser: true, useUnifiedTopology: true });

const Record = mongoose.model('Record', { name: String, age: Number });

app.get('/records', (req, res) => {
    Record.find({}, (err, records) => {
        if (err) {
            res.status(500).send('Error fetching records from the database');
        } else {
            res.json(records);
        }
    });
});
    

Now, when a GET request is made to the /records route, the server will fetch all the records from the database and send them back as a JSON response.

Finally, we can test our route using tools such as Postman or by making a request from a frontend application:

    
fetch('/records')
    .then(response => response.json())
    .then(data => console.log(data));
    

And that’s it! We have successfully created a route to fetch records from the database using Node.js and Express.js.