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
1 Answer
Reset to default 4For $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
版权声明:本文标题:javascript - How to filter data with sequelize - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741971524a2407868.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论