简体   繁体   中英

sequelize.js deep save model instance

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM