1

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

1 Answer 1

4

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.

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

2 Comments

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
I'm not sure what you mean. In my example, you're updating the product model. Which model are you looking to update?

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.