11

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!

2
  • did you find a solution? Commented Jul 18, 2017 at 14:08
  • I think it's easier to restore the whole json object in "jsonb" field.. (but maybe it's not so effecient) Commented Mar 25, 2018 at 8:33

4 Answers 4

2
+50

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

Sign up to request clarification or add additional context in comments.

3 Comments

@Shamoon, have you read this?stackoverflow.com/questions/23490965/…
can you please add the relevant information to your answer so this post is complete?
JSONB type is postgresql data type. Sequence is ORM mapper to DB. If postgresql (9.4) does not support certain operation like "-" for JSONB, you can't use those operations in ORM mapper neither. But from v9.5 support the operation and in Sequence "-" operation work.
1

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

Comments

0

Try this:

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

3 Comments

How is this different from existing answer?
It updates the database in a single Query. While yours does 2 queries. 1 to fetch the data and second to update.
This is more practical because it can bulk update any number of records with one query
0

With Sequelize 6 (and maybe earlier), you can do the following on your model instance:

 delete myRecord.jsonBField.keyName; 

Then call changed (required) to mark the field as changed and save:

 myRecord.changed("jsonBField", true);
 myRecord.save();`

Alternatively, you can call myRecord.set("jsonBField.keyName", null) to set the key to null, which will automatically mark the field as changed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.