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
Answer could be very well found in its documentation at :- https://www.mongodb.com/docs/drivers/node/current/quick-reference/
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
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: