X
X
xutegino2017-09-10 00:19:34
MongoDB
xutegino, 2017-09-10 00:19:34

How to return a message if nothing is found?

I'm running an ExpressJS server. There is a handler:

router.get('/articles/:section', Article.getArticlesBySection)

exports.getArticlesBySection = (req, res, next) => {
  Article.find({section: req.params.section})
    .then((articles) => {
      if (!articles) {
        // FIX THIS
        return res.status(404).json({
          message: 'Articles doesn\'t exist'
        })
      }
      return res.status(200).json(articles)
    })
    .catch((err) => {
      return next(err)
    })
}

I have 3 in total section. I want to return a message to the user if there is a call to a route that doesn't match my section. The problem is that if .findit doesn't find anything, then it doesn't work.
if (!articles) {
        // FIX THIS
        return res.status(404).json({
          message: 'Articles doesn\'t exist'
        })
      }

And it returns an empty array of the form []
How to handle this? Maybe I should use another Mongus method? Because it .findOneworks as intended with a similar code (I use it if the address of a specific note is wrong.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
oh, 2017-09-10
@xutegino

check array length?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question