I am currently trying to build a query for finding specfic object within a jsonb array. I have the following query which works fine if I used a hard coded string for the “game” value e.g.
JavaScript
x
7
1
const findGameQuery = `
2
select playing
3
from users
4
where username = $1
5
and playing @> '[{"game": "new-pokemon-snap"}]'
6
`
7
However, if I use a dynamic value like I currently do for username, I get invalid json syntax error. e.g.
JavaScript
1
10
10
1
const findGameQuery = `
2
select playing
3
from users
4
where username = $1
5
and playing @> '[{"game": $2}]'
6
`
7
8
const { rows } = await query(findGameQuery, [username, game]);
9
ctx.body = rows
10
How do I search using a dynamic value here? I have done a ton of searching and can’t find any examples. $2 value is just a string so not sure why not accepted.
Advertisement
Answer
When you send this query, it only has ONE parameter:
JavaScript
1
5
1
select playing
2
from users
3
where username = $1
4
and playing @> '[{"game": $2}]'
5
The correct query is:
JavaScript
1
5
1
select playing
2
from users
3
where username = $1
4
and playing @> $2
5
You have to make the array with the object in the parameter.
JavaScript
1
6
1
const gameObj = [{
2
"game": game
3
}];
4
const gameParam = JSON.stringify(gameObj);
5
const { rows } = await query(findGameQuery, [username, gameParam]);
6