skip to Main Content

I want to get the data from my MongoDB database depending on the URL . If I access localhost:3000/phones it should get all the data with the category phones, where if it is localhost:3000/laptops it should get all the laptops.

Below is my schema:

    name: {
        required: true,
        type: String
    },
    category: {
        required: true,
        type: String
    },

Below is how my current version:

router.get('/getAll', async (req, res) => {
    try {
        const data = await Model.find();
        res.json(data)
    }
    catch (error) {
        res.status(500).json({ message: error.message })
    }
})

I tried to findByID but it did not work.

2

Answers


  1. Answer could be very well found in its documentation at :- https://www.mongodb.com/docs/drivers/node/current/quick-reference/

    router.get('/phones', async (req, res) => {
        try {
            const data = await Model.find({category: "phones"});
            res.json(data)
        }
        catch (error) {
            res.status(500).json({ message: error.message })
        }
    })
    

    As the same query is used for phone and laptop requests you can refactor it
    to handle in the same endpoint by using query parameters in the request

    url will be of format:- localhost:3000/getAll?category=phones

    router.get('/getAll', async (req, res) => {
        try {
            const category = req.query.category
            const data = await Model.find({category: category});
            res.json(data)
        }
        catch (error) {
            res.status(500).json({ message: error.message })
        }
    })
    
    Login or Signup to reply.
  2. you should send your request with query param ?category=phones or ?category=laptops

    so then you can get your category from req.query.category.

    that is what you’re looking for:

    
    router.get('/getAll', async (req, res) => {
        try {
            const category = req.query.category;
    
            const data = await Model.find({
                category,
            });
    
            res.json(data)
        }
        catch (error) {
            res.status(500).json({ message: error.message })
        }
    })
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search