简体   繁体   中英

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. Roles are stored as an array of strings. For example ['student'] or ['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} . The documentation says that I can use the following instead for my $in query

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

Which removes the {} but it gives me a 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. I have to match the contents of roles exactly. For example, if a user has both admin and school_owner roles I have to say

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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