简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM