admin管理员组

文章数量:1315069

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
  }
}

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
  }
}
Share Improve this question asked Oct 3, 2017 at 20:45 Андрей ГузюкАндрей Гузюк 2,1646 gold badges31 silver badges56 bronze badges 3
  • You need to paas an array of tags in the $in like this $in : ['tag1', 'tag2', 'tag3'] – Sagar Jajoriya Commented Oct 4, 2017 at 5:11
  • @SKJajoriya, doesn't work getting error about [object Object] – Андрей Гузюк Commented Oct 4, 2017 at 6:23
  • Can you show me your tags es from the request that you pass in the query ? – Sagar Jajoriya Commented Oct 4, 2017 at 7:11
Add a ment  | 

1 Answer 1

Reset to default 4

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,
    },
  },
});

本文标签: javascriptHow to filter data with sequelizeStack Overflow