来自route.param查询的回调

时间:2016-02-18 12:27:24

标签: node.js express mongoose

我的服务器中有以下路由:

// 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);
  });
});

我正在尝试为路由参数post_id创建一个回调触发器,如下所示:

// 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();
  });
});

但是,执行此回调触发器后,我想继续执行查询(select方法),具体取决于路径。

我怎样才能做到这一点?这可能吗?起初,我正在使用User.findById()替换req.post,但这不起作用,因为req.post是第一个查询产生的实际对象。

1 个答案:

答案 0 :(得分:0)

要继续呼叫其他路线,您可以置于if条件:

// 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