Joffrey Hernandez
Joffrey Hernandez

Reputation: 1846

Sequelize always timeout when row doesn't exist in database

i have a get for an user with sequelize on a nodejs server :

router.get('/:id', function (req, res) {
  models.user.find({
      where: {
          id: req.params.id
      }
  }).then(function (result) {
      if (result === null) {
          res.status(204);
      } else {
          res.status(200);
          res.json(result);
      }
  });
});

working perfectly when user exist in database, but when i use an id who doesn't exist this get timeout, like every other find i use.

Someone could tell me what I'm doing wrong?

Upvotes: 1

Views: 778

Answers (1)

gyc
gyc

Reputation: 4360

If your result is null you set the status of the response but don't return anything.

Usual way to do this is the call next() to end the route:

router.get('/:id', function (req, res, next) {
    models.Utilisateur.find({
        where: {
            id: req.params.id
        },
        include: [{model: models.Profil, include: [{model: models.Fonctionnalite}], through: {attributes: []}}]
    }).then(function (result) {
        if (result === null) {
            res.status(204);
            next();
        } else {
            res.status(200);
            res.json(result);
        }
    });
});

or you could just return a json object instead.

res.json({error: "not found"});

Upvotes: 1

Related Questions