简体   繁体   English

Sequelize:查询字符串在字符串数组postgresql中

[英]Sequelize: where query string is in array of strings postgresql

I am trying to perform a query in sequelize where I want to get only users that have the correct role. 我正在尝试按sequelize执行查询,在此我只希望获得具有正确角色的用户。 Roles are stored as an array of strings. 角色存储为字符串数组。 For example ['student'] or ['school_owner', 'admin'] . 例如['student']['school_owner', 'admin']

In this particular case, I'm actually trying to get a school and include the school owners for that school. 在这种情况下,我实际上是在尝试建立一所学校,并包括该学校的学校所有者。 The failing relevant query is 失败的相关查询是

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 is storing the array values as something like {school_owner, admin} . sequelize将数组值存储为{school_owner, admin}类的东西。 The documentation says that I can use the following instead for my $in query 文档说,我可以在$in查询中使用以下内容

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

Which removes the {} but it gives me a Array value must start with "{" or dimension information.' 它删除了{}但它给了我一个Array value must start with "{" or dimension information.' error. 错误。

In the first example, the query doesn't fail, but it doesn't work like an $in query either. 在第一个示例中,查询不会失败,但也不会像$in查询那样工作。 I have to match the contents of roles exactly. 我必须完全匹配roles的内容。 For example, if a user has both admin and school_owner roles I have to say 例如,如果用户同时具有adminschool_owner角色,我必须说

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

What's the correct way to perform an $in query so that I can match all users that have a specific roles? 什么是执行$in查询的正确方法,以便我可以匹配具有特定角色的所有用户?

The correct way to implement this functionality is to do the following 实现此功能的正确方法是执行以下操作

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

This will return all users that have a role school_owner in their array of roles 这将返回所有在其roles数组中具有school_owner roles

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM