Sequelize - Filter FindAll by matching all Tags

Viewed 357
/assets/?tags[]=foo&tags[]=bar

Get requests to endpoint above should return only those records that contain ALL of the provided tags (foo,bar)

My current attempt is returning any records that match ANY of the given tags.

const { tags } = req.query;

res.send(
      await Asset.findAll({
        where: whereOptions,
        include: [
          { model: AssetMime },
          {
            model: Tag,
            as: 'tags',
            where: {
              title: {
                [Op.in]: tags,
              },
            },
          },
        ],
      })
    );

How can I modify my filter to return records where ALL tags match?

1 Answers

You can try Op.all operator instead of op.in if your DBMS supports ALL operator.

An alternative solution is to combine such conditions

const where = {}
if (tags && tags.length) {
  where[Op.and] = tags.map(x => ({ title: x })
}

await Asset.findAll({
        where: whereOptions,
        include: [
          { model: AssetMime },
          {
            model: Tag,
            as: 'tags',
            where: where,
          },
        ],
      })

Related