所以我基本上将一些查询字符串传递给我的端点以用作过滤器,我正在使用Sequelize。
我知道我可以使用where
来过滤/查找记录,但我想这样做,如果我不提供查询字符串,它就会被忽略。
当前:
const { status } = req.query;
const tickets = await models.Ticket.findAndCountAll({
where: {
status,
},
attributes: [
'id',
'status'
],
});
如果我没有将状态作为查询字符串传递,则由于where
无法执行而失败。我也尝试过将undefined
传递给它,但没有运气,它错误地说出来; ERROR: WHERE parameter "status" has invalid "undefined" value
总而言之,我想做到这一点,如果我提供查询字符串,它们会被插入到where
子句中,但如果它们不是,那么它就会被忽略。
如果您知道where
具有Sequelize可以使用的值,那么它只是包含status
选项的情况。
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);