Tutorial
Read Data from Database

Read Data from Database using Express & Mongoose

Read Data from Database using Express & Mongoose

▶️ Read Data from Database

  1. If you type the following command in the terminal npm run dev and open the browser and type http://localhost:5000/api/tasks you will see the following output.{ msg: 'Show all tasks }
  2. We need to show the data in the browser.
  3. Open your controllers/task.js file and add the following code.
const Task = require('../models/Task');

Imports the Task model from another file. This model defines how the data for each task is stored and validated in a database.

and inside async function add the following code.

   const myData = await Task.find({});
  • Uses an async function to query the database and find all the tasks. The await keyword pauses the execution until the promise is resolved or rejected. The result is assigned to a variable called myData.
  • The find() method returns all documents in a collection that match the query criteria. In this case, we are not passing any query criteria, so it will return all the documents in the collection.
  • You can check the official documentation of mongoDb find() method here (opens in a new tab).

and pass the myData to the res.json() function.

   res.json(myData);

The res.json() function sends a JSON response. The JSON response is sent with the following properties.

  1. Now if you check the browser you will see the following output.

image

  1. Now do this for testing also
const Task = require('../models/Task');
 
const getAllTasks = async(req, res) => {
   const myData = await Task.find({});
 
    res.status(200).json({ myData });
  };
 
const getAllTasksTesting = async(req, res) => {
    const myData = await Task.find({});
    res.status(200).json({ myData });
  };
 
module.exports = {
    getAllTasks,
    getAllTasksTesting
  };
  1. You can also filter the data by using the query parameters. For example, if you want to filter the data by the name of the task, you can use the following code.
const Task = require('../models/Task');
 
const getAllTasks = async(req, res) => {
   const myData = await Task.find({});
 
    res.status(200).json({ myData });
  };
 
const getAllTasksTesting = async(req, res) => {
    const myData = await Task.find({status: "incomplete"});
    res.status(200).json({ myData });
  };
 
module.exports = {
    getAllTasks,
    getAllTasksTesting
  };

image