Search code examples
javascriptnode.jssequelize.jsbluebird

sequelize error: Unhandled rejection TypeError: expecting an array or an iterable object but got [object Null]


I'm trying to use findOne from sequelize in my model, but I'm receiving this error The table that the model is referencing is empty, how to handle this?

Unhandled rejection TypeError: expecting an array or an iterable object but got [object Null]

This is my code:

app.get('/test/models', function(req, res) {

        var values = { 
            where: { user_id: 7 } 
        };

        MercadoLibre.findOne(values)
        .spread(function(err, meli) {

            console.log(err);

            if (typeof meli !== null) {
                console.log("undefined");
            } else {
                console.log(meli);    
            }

            res.redirect('/dashboard');
        });
    });

How can I fix this?


Solution

  • There are a few bugs in your code

    • You should be handling a Promise.reject() result from MercadoLibre.findOne().
    • You should get the results of findOne() using .then(), not .spread()

      .then(function(resolve)).catch(function(reject))

      • You can handle resolve() and reject() in a single thenable, but the format is:

        .then(function(resolve), function(reject))

    • You are checking for null incorrectly (no need for typeof), and your code will always return true (even if meli is undefined, so will the typeof)

      typeof meli !== null

    app.get('/test/models', function(req, res) {
      var values = { 
        where: { user_id: 7 } 
      };
    
      MercadoLibre.findOne(values)
      .then(function(result) {
        // just check for false-y
        if (!result) {
          console.log('Nothing was returned!')
        }
        // redirect to the route you want
        res.redirect('/dashboard');
      })
      .catch(function(err) {
        // catch any errors
        console.log('Error, do some kind of redirect?!', err);
      });
    });