user5113508
user5113508

Reputation:

Sequelize Remove "where" if query isn't provided?

So I'm basically passing some query strings to my endpoint to use as filters, and I'm using Sequelize.

I know I can use where to filter/find records, but I want to make it so that if I don't provide a query string, it just gets ignored.

Current:

const { status } = req.query;

const tickets = await models.Ticket.findAndCountAll({
  where: {
    status,
  },
  attributes: [
    'id',
    'status'
  ],
});

If I don't pass status as a query string, it fails since where can't execute. I tried also passing undefined to it but no luck, it errors out saying; ERROR: WHERE parameter "status" has invalid "undefined" value

So to summarise, I want to make it so that if I do provide the query strings, they are inserted into the where clause, but if they aren't, then it's just ignored.

Upvotes: 1

Views: 2967

Answers (1)

Ankh
Ankh

Reputation: 5738

It's simply a case of only including the where options if you know status has a value Sequelize can use.

const { status } = req.query;

// declare our query options
const options = {
    where: {},
    attributes: [
        'id',
        'status'
    ]
};

// if status has a value (!== undefined), include it in the query
if (status !== undefined)
    options.where.status = status;

const tickets = await models.Ticket.findAndCountAll(options);

Upvotes: 6

Related Questions