'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?
Solution 1:[1]
Yes you can update a nested json property with sequelize using a single update query but you have to use the raw queries.
sequelize.query(`UPDATE users SET data = jsonb_set(data, '{email,verified}', 'true', true) WHERE id = 1`);
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wing-On Yuen |
| Solution 2 | jiminikiz |
