2017-08-24 111 views
0

我试图在sequelize中执行查询,我只想获取具有正确角色的用户。角色被存储为一个字符串数组。例如['student']['school_owner', 'admin']Sequelize:其中查询字符串在字符串数组中postgresql

在这个特殊的情况下,我实际上是在争取一所学校,并且包括那所学校的学校老板。发生故障的相关查询是

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查询,以便我可以匹配具有特定角色的所有用户的正确方法?

回答

0

实现此功能的正确方法是做到以下几点

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

这将返回有一个角色school_owner所有用户在他们的roles

阵列