Open vishwaefor opened 5 years ago
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)); });
Steps