Hi I have a table where I use JSONB to store Nested JSON data and need to query this JSONB column Below is the structure of the table
{
"id": "5810f6b3-fefb-4eb1-befc-7df11a24d997",
"entity": "LocationTypes",
"event_name": "LocationTypes added",
"data": {
"event":{
"id": "b2805163-78f0-4384-bad6-1df8d35b456d",
"name": "builidng",
"company_id": "1dd83f77-fdf1-496d-9e0b-f502788c3a7b",
"is_address_applicable": true,
"is_location_map_applicable": true}
},
"notes": null,
"event_time": "2020-11-05T10:56:34.909Z",
"company_id": "1dd83f77-fdf1-496d-9e0b-f502788c3a7b",
"created_at": "2020-11-05T10:56:34.909Z",
"updated_at": "2020-11-05T10:56:34.909Z"
}
The code below is giving blank array as response
const dataJson = await database.activity_logs.findAll({
where: {
'data.event.id': {
$eq: 'b2805163-78f0-4384-bad6-1df8d35b456d',
},
},
raw: true,
});
Is there any way I can accomplish querying nested json object using sequelize in a better way .
You should try sequelize.literal
with JSON-operators/functions wrapped into sequelize.where
. Something like this:
sequelize.where(sequelize.literal("data->'event'->'id'"), '=', 'b2805163-78f0-4384-bad6-1df8d35b456d')
more recent syntax (not sure from what Sequelize version it starts to work) to construct conditions against JSON:
{
data: {
event: {
id: 'b2805163-78f0-4384-bad6-1df8d35b456d'
}
}
}