简体   繁体   中英

What is the below express router doing?

The tutorial that I am following has the following 2 router methods for getting the articles from db.

router.param('article', function(req, res, next, slug) {
  Article.findOne({ slug: slug})
    .populate('author')
    .then(function (article) {
      if (!article) { return res.sendStatus(404); }

      req.article = article;

      return next();
    }).catch(next);
});

router.get('/:article', auth.optional, function(req, res, next) {
  Promise.all([
    req.payload ? User.findById(req.payload.id) : null,
    req.article.populate('author').execPopulate()
  ]).then(function(results){
    var user = results[0];

    return res.json({article: req.article.toJSONFor(user)});
  }).catch(next);
});

I have two questions regarding the methods above,

  1. How does Promise.all() work ?
  2. Why do we need to repopulate author field in router.get() method when already did that in the router.param() method?
  1. Promise.all(iterables) is used when you have multiple promises that you need to be done before executing other task. In the given case

    [ req.payload ? User.findById(req.payload.id) : null, [ req.payload ? User.findById(req.payload.id) : null, req.article.populate('author').execPopulate() ]

  2. Populate will not be executed until a callback is passed or execPopulate is called . So your router param will not actually populate('author'). the .then just attaches it to the req.article. When you call populate again with same path('author') then it resets any query options that was set by the previous populate call.

this is mentioned in the Mongoose docs also here at the end as a note

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM