Андрей Гузюк
Андрей Гузюк

Reputation: 2164

How to filter data with sequelize

Trying to filter data with sequelize but it seems doesn't work

I have in my model tags which have following data tags: [{id: 1, name: 'Hey'}]. So i'm trying to get all records from this model where tags match tags what came from request. ( They have similar data tags: [{id: 1, name: 'Hey'}]. But i have all records -> should only one

where: {
  tags: {
    $in: req.body.tags
  }
}

Upvotes: 4

Views: 18304

Answers (1)

maxim.u
maxim.u

Reputation: 351

For $in condition your tags should be array of values, not array of objects.

Wrong:

tags: [{id: 1, name: 'work'}, {id: 2, name: 'party'}, ... ]

Correct:

// tags contains name|title of tags. now this is your choice.
tags: ['work', 'party', 'whatever', ...]

// tags contains id's of tags. for this you should change your where condition.
tags: [1, 2, 3, ...]

Example:

const tagsFromRequest = [{ id: 1, name: 'work' }, { id: 2, name: 'party' }];

const tagsIds = tagsFromRequest.map(tag => tag.id);
const tagsNames = tagsFromRequest.map(tag => tag.name);

const tagsByIds = await DB.tag.findAll({
  where: {
    id: {
      $in: tagsIds,
    },
  },
});

const tagsByNames = await DB.tag.findAll({
  where: {
    name: {
      $in: tagsNames,
    },
  },
});

Upvotes: 4

Related Questions