vishwaefor / article-hub

This is a REST API using NodeJS Express + MongoDB
Apache License 2.0
0 stars 37 forks source link

Implement endpoints for other actions #14

Open vishwaefor opened 5 years ago

vishwaefor commented 5 years ago

Steps

router.get('/:id/comments', (req, res, next) => {
  Articles.findById(req.params.id)
    .then(
      r => {
        if (r) {
          return Comments.find({
            _id: {
              $in: r.comments
            }
          }).populate('author');
        } else {
          const error = new Error('no article found');
          error.status = 404;
          throw error;
        }
      },
      err => {
        const error = new Error('invalid article id');
        error.status = 400;
        throw error;
      }
    )

    .then(comments => {
      res.status(200).json({
        results: comments.map(c => {
          return {
            id: c._id,
            comment: c.comment,
            author: { name: c.author.name, id: c.author._id },
            createdAt: c.createdAt
          };
        })
      });
    })
    .catch(err => next(err));
});