简体   繁体   English

如何使用sequelize过滤数据

[英]How to filter data with sequelize

Trying to filter data with sequelize but it seems doesn't work 尝试使用sequelize过滤数据,但似乎不起作用

I have in my model tags which have following data tags: [{id: 1, name: 'Hey'}] . 我的模型tags中包含以下数据tags: [{id: 1, name: 'Hey'}] So i'm trying to get all records from this model where tags match tags what came from request. 所以我想从这个模型中,所有的记录tags匹配tags从请求什么来。 ( They have similar data tags: [{id: 1, name: 'Hey'}] . But i have all records -> should only one (他们有类似的数据tags: [{id: 1, name: 'Hey'}] 。但是我有所有记录->应该只有一个

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

For $in condition your tags should be array of values , not array of objects . 对于$ in条件,标记应为值 数组 ,而不是对象数组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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