Search code examples
postgresqlsequelize.jsjsonb

Sequelize JOSNB Query


I have a table with JSONB column in Postgres which is having structure like this

{"Name":"f","District Name":"ky","Age":"21","Gender":"M"}

    MyTable.findAll({
       where: {
          'userData.Age':{
            $lt: age,
          }
       }
    })

Converted to Query

SELECT "id", "uuid", "device_id", "version", "userData", "createdAt", "updatedAt" 
FROM "MyTable" AS "MyTable" 
WHERE CAST(("MyTable"."userData"#>>'{Age,$lte}') AS DOUBLE PRECISION) = 40;

Next Query is

MyTable.findAll({
   where: {
    'userData.Gender':{
        $eq: 'M',
    }
   }
})

Converted to Query

SELECT "id", "uuid", "device_id", "version", "userData", "createdAt", "updatedAt" 
FROM "MyTable" AS "MyTable" 
WHERE ("MyTable"."userData"#>>'{Gender,$eq}') = 'M';

Both are returning empty Records, I can think of Age not working as it is text in JSON, but Gender should work.

with this raw queries I am getting records.

select uuid from "MyTable" where ("userData"->>'Age') :: Integer < 50;

select uuid from "MyTable" where ("userData"->>'Gender') = 'M';

Solution

  • ("MyTable"."userData"#>>'{Gender,$eq}') = 'M' shows that there is an issue with Sequelize query and reason could be $lte and $eq operators are not working, as operator Aliasing not supported now. Use Op.lte or Op.eq instead.