Home > Software engineering >  Express.js Query Based on URL Parameter?
Express.js Query Based on URL Parameter?

Time:11-07

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.

CodePudding user response:

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 })
    }
})

CodePudding user response:

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 })
    }
})

  • Related