【发布时间】:2017-08-24 20:30:25
【问题描述】:
我希望使用 Sequelize 从 postgres 数据库中提取项目,但只返回 ID 不等于给定数组中任何项目的项目。
在Sequelize documentation 中,有$ne 用于not equal 和$in 的运算符用于返回具有与给定数组匹配的值的属性的项目,但看起来没有用于某事的运算符结合了这两者。
例如,如果我的数据库中有 ID 为 [1, 2, 3, 4, 5, 6] 的项目,并且我想通过与另一个数组(即 [2,3,4])进行比较来过滤这些项目,以便它返回项目 [1, 5, 6]。在我的示例中,我还随机化了退货顺序和限制,但这可以忽略。
function quizQuestions(req, res) {
const query = {
limit: 10,
order: [ [sequelize.fn('RANDOM')] ],
where: {
id: { $ne: [1, 2, 3] } // This does not work
}
};
Question.findAll(query)
.then(results => res.status(200).json(map(results, r => r.dataValues)))
.catch(err => res.status(500).json(err));
}
编辑:使用@piotrbienias 的答案,我的查询如下所示:
const query = {
limit: 10,
order: [ [sequelize.fn('RANDOM')] ],
where: {
id: { $notIn: [1, 2, 3] }
}
};
【问题讨论】: