Sequelize optional where clause parameters?

You could build the where object beforehand. Here's a simple example

// Get typeIds from whatever source you have

// Here's an example
var typeIds = [1, 2, 3];

// Or you could try this to build a query without typeIds
// var typeIds = [];

var whereCondition = {};

if (typeIds.length > 0) {
    whereCondition['$or'] = typeIds.map(function(id) {
        return {
            typeId: id
        };
    })
};

whereCondition['cityId'] = 1;

console.log(whereCondition);

Post.findAll(whereCondition).then(function(posts) {
    // The rest of your logic
});

You can do this:

Post.findAll({
     where: {
          cityId: 1,
          ...(types && types.length && {
              types
          })
      }

types attr will only be evaluated in the expression if the array has elements.

Tags:

Sequelize.Js