My problem is that I don't get the id of parent resource in req.params in routes of subresources. Come with me ... I'll show you ...
Here's the relevant parts in my code:
- routes/
- index.js
- countries.js
- cities.js
- controllers/
- cities.js
index.js
let router = require('express').Router();
router.use('/countries', require('./countries'));
router.use('/countries/:countryId/cities', require('./cities'));
module.exports = router;
routes/countries.js
const router = require('express').Router();
const countries = require('../controllers/countries');
router.post('/', countries.create);
router.get('/', countries.readAll);
router.get('/:_id', countries.readById);
router.patch('/:_id', countries.updateById);
router.delete('/:_id', countries.deleteById);
module.exports = router;
routes/cities.js
const router = require('express').Router();
const cities = require('../controllers/cities');
router.get('/', cities.readAll);
router.get('/:_id', cities.readById);
module.exports = router;
controllers/cities.js
module.exports.readAll = async function (req, res, next)
{
return res.json(req.params);
};
module.exports.readById = async function (req, res, next)
{
return res.json(req.params);
};
Now, the problem is as follows:
If I call the following API:
GET countries/1/cities
The result is {} When it should actually send me back {"countryId":"1"}
Also, when I call the following API:
GET countries/1/cities/2
The result is {"_id": "2"} When it should actually send me back {"countryId":"1", "_id": "2"}
So the problem is for some reason, the id of the parent resource (countryId) is not accessible in the controller of the child resource.
Please advise