尝试使用sequelize过滤数据,但似乎不起作用
我的模型标签
中有以下数据标签:[{id: 1, name: 'Hey'}]
。所以我试图从这个模型中获取所有记录,其中 tags
与来自请求的 tags
匹配。 (他们有相似的数据标签:[{id: 1, name: 'Hey'}]
。但我有所有记录 -> 应该只有一个
where: {
tags: {
$in: req.body.tags
}
}
最佳答案
对于$in条件,您的标签应该是值数组,而不是对象数组。
错误:
tags: [{id: 1, name: 'work'}, {id: 2, name: 'party'}, ... ]
正确:
// 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, ...]
示例:
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,
},
},
});
关于javascript - 如何使用sequelize过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553128/