Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: delete JSONB property (with PostgreSQL)

I'm using sequelize (v3.12.2), with pg (4.4.3), PostgreSQL (v9.4), and Node (v4.1.2).

I have a model that inlcudes a JSONB data type field.

var User = {
  data: {
    type: Sequelize.JSONB
}

Now I can do

User.findOne({where: {id: 12345}})
  .update({data: {x: 'foo'}});

And

User.findOne({where: {id: 12345}})
  .update({'data.y': 'bar'});

Now, if I want to delete just the data.x property how can I do it in one command?

User.findOne({where: {id: 12345}})
  .update({'data.x': null});

Obviously doesn't work. In fact, the resulting data object should be:

{y: 'bar'}

And not:

{x: null, y: 'bar'}

How can I do this with Sequelize? Thanks for your help!

like image 354
Pensierinmusica Avatar asked Oct 20 '15 16:10

Pensierinmusica


2 Answers

If @Tarun Lalwani's code does not work, probably Your postgresql 9.4 does not support "-" operation.

In that case, creating function or upgrade to 9.5+ would be your option.

See PostgreSQL: Remove attribute from JSON column

like image 57
John Avatar answered Sep 27 '22 18:09

John


I think below should work

User.findOne({where: {id: 12345}})
  .update({'data': sequelize.literal("data - 'x' ")});

Have not tested it, but if it doesn't work let me know. The solution will be along these lines only

like image 34
Tarun Lalwani Avatar answered Sep 27 '22 16:09

Tarun Lalwani