0

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.

1 Answers1

0

To continue call another routes, you can put inside if condition:

// Associated with the parameter 'timeline_id' - executed for every route
router.param('post_id', function(req, res, next, post_id) {
  Post.findById(post_id, function (err, post){
    if (err) {
    return next(new Error("Couldn't find user: " + err));
  }

    // if no post is found
    if(!post) {
      return res.status(404).send({ message: { post: 'There is no such timeline.'} });
      // something bad happened! The requested timeline does not exist.
      next();
    }

    req.post = post;
    next();
  });
});

Want see

Community
  • 1
  • 1
BrTkCa
  • 4,703
  • 3
  • 24
  • 45
  • That is what I have in my code! The problem is that, then, for my routes I get the following error `(req.post).select(...).exec is not a function`! –  Feb 18 '16 at 13:37
  • Actually, with select it wouldn't be a problem, I could manually get the required information into a new object. But what if I want to use `populate` after? The same error occurs: `(req.post).populate(...).exec is not a function` –  Feb 18 '16 at 13:48