2017-08-24 113 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

陣列