Sequelize: using build to update a record

走远了吗. 提交于 2019-12-10 18:16:17

问题


Let's say I have the following simple model:

var Foo = sequelize.define('Foo', {
    bar: Sequelize.STRING,
});

And the table Foos in the database has a record:

id   bar
---  ---
1    abc

In order to update this record I could do the following:

Foo.findById(1).then(function(foo) {
    foo.bar = 'xyz';
    foo.save();
});

Now I have found another way to update the record without having to find it form the database:

var foo = Foo.build({ id: 1, bar: 'xyz' });
foo.isNewRecord = false;  // makes save use UPDATE instead of INSERT INTO
foo.save();

This is perfect for my use case, but I'm wondering if I'm breaking anything in sequelize.


回答1:


There is a parameter in the build function that takes an object called options. options has an attribute isNewRecord that defaults to true. If you set this to false and use update() it will update the existing record after you set the primary key.

let instance = await db.Model.build({}, {isNewRecord: false});
const result = await instance.update({
    id: instanceId,
    column : newValue
});

source



来源:https://stackoverflow.com/questions/41286833/sequelize-using-build-to-update-a-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!