'Working code below to fetch all the data from my MongoDb databse but now I want to only fetch based on lets say courses category. How can I do it?

Below is a working code that I used to fetch all my data from my MongoDb database. It worked fine and now I am looking to only fetch based on certain criteria. Lets say I have list of courses with title, description, category, and price. I want to only show the ones with category that says 'coding. How can I do it? This is React Code

import "./style/courses.css";
import {
  Link
} from "react-router-dom";
import React, {
  useEffect,
  useState
} from "react";
import './style/home.css';

function Course() {
  const [courses, setCourses] = useState([]);

  useEffect(() => {
    fetch("http://localhost:8000/courses")
      .then(response => response.json())
      .then(data => {
        setCourses(data); // set users in state
      });
  }, []); // empty array because we only run once



  return (
    courses.map(course => {
      return ( <
        div className = "main"
        key = {
          course._id
        } >
        <
        div className = "product" >
        <
        img src = {
          course.image
        }
        alt = {
          course.title
        }
        />

        <
        div className = "product__info" >
        <
        p className = "info__name" > {
          course.title
        } < /p> <
        p className = "info__name" > {
          course.category
        } < /p>

        <
        p className = "info__description" > {
          course.description.substring(0, 100)
        }... < /p>

        <
        p className = "info__price" > $ {
          course.price
        } < /p>


        <
        Link to = {
          `/courses/${course._id}`
        }
        className = "info__button" >


        View <
        /Link>

        <
        /div> <
        /div> <
        /div>
      )
    })
  )
}
export default Course;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

This is backend routes

const express = require("express");
const mongoose = require("mongoose");
const router= express.Router()

const categoryController = require("../controllers/categorycontroller.js");

router.route('/').get(categoryController.findCategory);

module.exports=router

with initial route

app.use('/courses/category', categoryeRoute)

This is controller

const Category = require("../models/course");

//find course by category
exports.findCategory = async (req, res) => {
    try {
      const Categoryquery = req.query.category;
      const firstCategory = await Category.find({category:Categoryquery});
      res.send(firstCategory);
    } catch {
      res.status(404).send({ error: "category is not found!" });
    }
  };


Solution 1:[1]

Your code is excellent... This line const firstCategory = await Category.find({category:Categoryquery}) When using your postman or any software you used to test your API I believe for the category you must have used a direct value like const firstCategory = await Category.find({category:"science"}) this will in turn display only science category.

But the major reason why your code isn't working is because of you need to send a value to filter the courses since when you already have this line

const Categoryquery = req.query.category;

I suggest using a drop-down with all the categories in the frontend. So that you can inturn use onChange to pass the category value to the backend. But req.query here simply means you will extract the data from your url.

Check this out

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1