postgresql - Sequelize.js:查询不在数组中(数组中的项目为 $ne)

标签 postgresql sequelize.js

我希望使用 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] }
    }
  };

最佳答案

使用

const Op = Sequelize.Op
where: {
      id: {[Op.notIn]:[1, 2, 3]}
}

参见 operators :

Sequelize exposes symbol operators that can be used for to create more complex comparisons

关于postgresql - Sequelize.js:查询不在数组中(数组中的项目为 $ne),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43125925/

相关文章:

sequelize.js - 如何在 sequelize.js 中使用子查询?

java - Spring Boot 不会在 Postgres 中创建表

ruby-on-rails - Postgres 仅排序字母数字

Postgresql:在用户定义类型中,发送函数的用途是什么?

postgresql 中的字符串文字和转义字符

sql - 将同一表中的其他记录数组添加到每条记录

sql - 数据库对不可变字段的支持

node.js - 如何在 Sequelize 中使用 and 运算符

javascript - 在 Sequelizejs 中使用不同的 mysql 用户

javascript - 如何在 Sequelize 中创建自引用外键?