How to add a nested JSONB field with sequelize/postgres

In User model, there is a JSONB field viewer_data which is currently null for instance user. A new field jwt_secret with value 1 needs to be added under viewer_data. It shall look like the following after adding jwt_secret under viewer_data:

  user : {viewer_data : {"jwt_token":1}}

Tried the set and insert and both of them are not working:

   user = await User.findByPk(id);
   console.log(user.viewer_data); //<<==output is null 
   user.set("viewer_data.jwt_secret", 1); //<<==throw an error of can't convert null to object as viewer_data is null
   user.insert("view_data.jwt_secret", 1); //<<==error as insert is not a function

The postgres version is 11 and sequelize is 6.3.

1 answer

  • answered 2020-09-14 19:11 user938363

    When the JSONB field viewer_data is null. a update shall be done like this:

      user.set("viewer_data", {"prev_jwt_secret": xxx, "jwt_secret": xxx}};