Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize update nested property in JSONB

I am looking for a way to update only a nested key/value inside jsonb column.
here is the User model:

const User= sequelize.define('User', {
    id: DataTypes.INTEGER,
    name:DataTypes.STRING,
    // other fields
    data: DataTypes.JSONB
});

current data column value:

{
 'email':{'verified':false,'token':'random token'},
 'phone:{'verified':true}
}

I want to update email.verified property to true using a single update query.

I tried following codes:

models.User.update({'data.email.verified':true},
       {where:{id:1}}).then()...

models.User.update({data:{email:{verified:true}}},
       {where:{id:1}}).then()...

the updated column would be:

{
 'email':{'verified':true},
}

I also tried this:

models.User.findById(1).then(user => {
    user.set('data.email.verified', true);
    user.save().then()...
});

this works but i don't want to execute two query (select and then update) for only updating a field.

Is it possible to do this using sequelize with a single update query?

like image 591
Ali Sherafat Avatar asked Apr 14 '26 16:04

Ali Sherafat


1 Answers

model.yourJsonB.userName

model.yourJsonB.userName = "Lisa" // traditional prop change
model.changed("yourJsonB", true)   // << forces sequelize to understand this json has been updated
await model.save()

I found this here: https://sequelize.org/master/manual/upgrade-to-v6.html

like image 106
Naruto Uzumaki Avatar answered Apr 17 '26 12:04

Naruto Uzumaki