Picture this scenario:
{
"_id": "2020 Standings",
"DriversChampionship": [
{
"_id": "5fd3966d2769dc12dc010475",
"driverName": "Lewis Hamilton",
"driverTeam": "Mercedes AMG",
"driverPts": "230"
},
{
"_id": "5fd3966d2769dc12dc010476",
"driverName": "Sebastian Vettel",
"driverTeam": "Ferrari",
"driverPts": "161"
}
],
"ConstructorsChampionship": [
{
"_id": "5fd3966d2769dc12dc010489",
"teamName": "Mercedes AMG",
"teamPts": "230"
},
{
"_id": "5fd3966d2769dc12dc01048a",
"teamName": "Ferrari",
"teamPts": "161"
}
]
}
In the Routes folder, I have created a GET request as follows:
router.route("api/standings/:arrayName")
.get(getStandingsArray);
How can Mongoose find and send a res.json response with only the array that matches the :arrayName?
Let me illustrate with an example:
If I access the route
http://localhost:4000/api/standings/DriversChampionship
The controller extracts the :arrayName
using...
const arrayName = req.params.arrayName
// arrayName = DriversChampionship
and then retrieves and displays this particular array of objects using modelName.find()
...
"DriversChampionship": [
{
"_id": "5fd3966d2769dc12dc010475",
"driverName": "Lewis Hamilton",
"driverTeam": "Mercedes AMG",
"driverPts": "230"
},
{
"_id": "5fd3966d2769dc12dc010476",
"driverName": "Sebastian Vettel",
"driverTeam": "Ferrari",
"driverPts": "161"
}
]
I'm still trying to figure out how to accomplish this with Mongoose.
Any suggestions or ideas?
Feel free to ask if any part of my explanation is unclear
Thank you!