I have the following routes in my server:
// Fetch the information (description and tags) of a post
router.get('/:post_id/information', function(req, res) {
User.findById(req.params.post_id)
.select('data.title.text tags')
.exec(function(req, post) {
res.json(post);
});
});
// Fetch the media object of a post
router.get('/:post_id/media', function(req, res) {
User.findById(req.params.post_id)
.select('data.media')
.exec(function(req, post) {
res.json(post);
});
});
And I was trying to create a callback trigger to the route parameter post_id
, like so:
// Associated with the parameter 'post_id' - executed for every route
router.param('post_id', function(req, res, next, post_id) {
Post.findById(post_id, function (err, post){
if(err) { throw err; }
// if no post is found
if(!post) {
return res.status(404).send({ message: { post: 'There is no such post.'} });
// something bad happened! The requested post does not exist.
}
req.post = post;
return next();
});
});
But, after executing this callback trigger, I would like to continue to perform my queries (select
methods) depending on the route.
How can I achieve this? Is this possible? At first, I was replacing User.findById()
with req.post
, but this does not work since req.post
is the actual object resulting from the first query.