postgresql - Sequelize : where query string is in array of strings postgresql

标签 postgresql sequelize.js

我正在尝试在 sequelize 中执行查询,我希望只获取具有正确角色的用户。角色存储为字符串数组。例如 ['student']['school_owner', 'admin']

在这种特殊情况下,我实际上是在尝试获取一所学校并包括该学校的学校所有者。失败的相关查询是

const ownerQuery: { [key: string]: any } = {};
ownerQuery.roles = {$in: ["{school_owner}"]};

School
  .findById(req.params.id,{include: [{ model: User, where: ownerQuery }]})
  .then((school: School | null) => {
    if (school === null) {
      res.status(404).json({message: "Not Found"})
    } else {
      res.json(school)
    }
  }, (error) => next(error))

sequelize 将数组值存储为类似于 {school_owner, admin} 的内容。 documentation说我可以使用以下代替我的 $in 查询

ownerQuery.roles = {$in: ["school_owner"]};

它删除了 {} 但它给我一个 Array value must start with "{"or dimension information.' 错误。

在第一个示例中,查询没有失败,但它也不像 $in 查询那样工作。我必须完全匹配 roles 的内容。例如,如果用户同时具有 adminschool_owner 角色,我不得不说

ownerQuery.roles = {$in: ["{school_owner, admin}"]};

执行 $in 查询以便匹配具有特定角色的所有用户的正确方法是什么?

最佳答案

实现此功能的正确方法是执行以下操作

ownerQuery.roles = { $contains: ["school_owner"] };

这将返回在他们的roles数组中具有school_owner角色的所有用户

关于postgresql - Sequelize : where query string is in array of strings postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45865054/

相关文章:

postgresql - Sequelize 错误 - "model.get is not a function"

sequelize.js - Sequelize - 引用相同表主键的外键

mysql - 如何在 Moleculer.js 中使用 Sequelize ORM 原始查询(内联或已经准备好的 SQL 查询)

javascript - SequelizebelongsToMany 关联不起作用

associations - Sequelize ORM,Hooks 不与关联一起工作

angularjs - 基于标志在 Sequelize 中添加 "where"查询

ruby - ActiveRecord::AdapterNotSpecified 数据库配置没有指定适配器

database - PostgreSQL:只读用户

PostgreSQL 连接以使用 generate_series 对表进行非规范化

postgresql - createuser : error: could not connect to database postgres, - Docker AWS