Tutorial
Improve Filter in API

Improve Filter in API & Make API Work Better

Add Filter in API & Make API Work Better

▶️ Problem Statement

  1. If you change some data and again hit node tasksDB.js then it will create duplicate data in database.
  2. Assume if I send a invalid request to API but one is correct then API should return the correct response instead of this. image

▶️ Solution

  1. Simple solution is to add deleteMany() method in tasksDB.js file.
testDB.js
require("dotenv").config();
const connectDB = require("./db/connect");
const Task = require("./models/task");
const tasksJSON = require("./tasks.json");
 
const start = async () => {
  try {
    await connectDB(process.env.MONGODB_URL);
    await Task.create(tasksJSON);
    await Task.deleteMany();
    console.log("Tasks created successfully");
    process.exit(0);
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
};
 
start();
  1. If any condition is not matched then we should see the data which is matched.
  • Go to controllers/task.js file and add this code.
controllers/tasks.js
 
const {priority} = req.query;
   const queryObject = { };
 
   if(priority) {
        queryObject.priority = priority;
        console.log(queryObject.priority);
    }

Now if you hit http://localhost:5000/api/tasks?priority=urgent&ahkh then it will return the data which is matched with priority.

example

Change the image size by using the click-and-scroll function.

controllers/tasks.js <- full code
 
const Task = require('../models/Task');
 
const getAllTasks = async(req, res) => {
 
   const {priority} = req.query;
   const queryObject = { };
 
   if(priority) {
        queryObject.priority = priority;
        console.log(queryObject.priority);
    }
 
  const myData = await Task.find(queryObject);
 
    res.status(200).json({ myData });
  };
 
const getAllTasksTesting = async(req, res) => {
    const myData = await Task.find(req.query);
 
    res.status(200).json({ myData });
  };
 
module.exports = {
    getAllTasks,
    getAllTasksTesting
  };