node js表示填充

时间:2018-03-13 14:06:03

标签: node.js express mongoose

发现这段代码不是那么直截了当,并且想知道是否有人可以帮助我清理方法正在做什么。

// return an article's comments
router.get('/:article/comments', auth.optional, function(req, res, next){
  Promise.resolve(req.payload ? User.findById(req.payload.id) : null).then(function(user){
    return req.article.populate({
      path: 'comments',
      populate: {
        path: 'author'
      },
      options: {
        sort: {
          createdAt: 'desc'
        }
      }
    }).execPopulate().then(function(article) {
      return res.json({comments: req.article.comments.map(function(comment){
        return comment.toJSONFor(user);
      })});

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

从我最初阅读的方法开始:

  1. 检查我们的有效负载,如果它不为null,我们发现用户返回null
  2. 然后我们将用户传递给我们的函数(用户)方法并返回req.article.populate()。我不完全确定为什么我们需要{path:' comments',populate:{path:..} ..}部分
  3. 然后我们execPopulate()。然后返回json doc
  4. 当我们在底部执行execPopulate时,我很困惑为什么我们需要在第一个populate上设置路径

1 个答案:

答案 0 :(得分:1)

我已清理嵌套的promises以使用async-await使其更加同步。你正走在正确的道路上,但我认为这会有很大的帮助:

async function handleRoute(req, res, next) {
    try {
        const id = req.payload ? req.payload.id : null
        const user = await User.findById(id).exec()

        if (!user) {
            throw new Error('User does not exist')
        }

        const populateOptions = {
            path: 'comments',
            populate: {
              path: 'author'
            },
            options: {
              sort: {
                createdAt: 'desc'
              }
            }
        }

        const article = await req.article.populate(populateOptions).execPopulate()
        const comments = article.comments.map(comment => comment.toJSONFor(user))

        res.json({ comments })
    } catch (error) {
        next(error)
    }
}

router.get('/:article/comments', auth.optional, handleRoute)
相关问题