Reputation: 28428
With sequelize, I am trying to update a nested attribute without success:
const Product = sequelize.define('product', {
title: { type: Sequelize.STRING },
color: { type: Sequelize.STRING },
});
const User = sequelize.define('user', {
name: { type: Sequelize.STRING },
});
Product.belongsTo(User);
User.hasMany(Product);
// create some data
await User.create({
name: 'foo',
products:[
{ title: 'prod1', color:'blue' },
{ title: 'prod2', color:'red' },
]
},
{ include: [ Product ] }
);
// query data
var data = await sequelize.models.user.findOne({
where: { name:'foo' },
include: [ Product ]
});
// update data
data.products[0].color = 'green';
await data.save();
// result
var data = await sequelize.models.user.findAll({
include: [ Product ]
});
Here, the product color is still blue. I wondering what is going wrong
edit1: I need to update from the "root" of my model because data update come from a JSON structure, and data of included models are part of this structure
Upvotes: 1
Views: 962
Reputation: 4790
You need to call update
on the instance of the product
model:
await data.products[0].update({
color: 'some other color'
});
As it stands now, you are just changing the value of the object returned by findOne
. When you call save
, the instance of the model does not know that you changed any values yet.
Upvotes: 4