Reputation: 13827
I cannot convince why my sequelize models is not updated when I add new column in table.
I've added new column 'status INTEGER' in my table and updated as follow in Models of my table in sequelize. When I retrieve value from my table, it coming nothing.
},
status: {
type: DataTypes.INTEGER,
default: 0
}
Please help me how to solve that issue. And even I've run migration as follow.
module.exports = {
up: function (migration, DataTypes, done) {
function addDisabledColumn() {
return migration.addColumn('applications', 'status',
{
type: DataTypes.INTEGER,
default: 0
}
)
}
addDisabledColumn().then(function () {
done();
}, function (err) {
done(err);
});
},
down: function (migration, DataTypes, done) {
done()
}
};
Upvotes: 4
Views: 6179
Reputation: 324
Now, if you take a look in API Reference and scroll to public async sync
method. You will see alter
option with drop
which means we can use sequalize.sync({alter:true, drop: false})
to update model columns without drop statement.
It should update missing columns on table and would be safe to use on production.
Upvotes: 1
Reputation: 2424
When I retrieve value from my table, it coming nothing.
The same thing happened to me. I created a migration that added a column to a table. When I would use .findAll
, .findOne
, findAllAndCount
, etc. the column wouldn't be present.
You can get the new column in two ways:
Add the new column to the model definition. This is needed not only to get the new column with .find
queries but to also be able to save the column when calling .create
. If that doesn't work:
Use attributes
and explicitly define the new column to be retrieved:
const employee = await Employee.findOne({
where: { id: id },
attributes: ['id', 'name', 'NEW_COLUMN'],
});
If you're going to query the table in several places, it's best to create an alias with the fields you want to query and use it everywhere you run find queries:
const Employee = sequelize.define('employee', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
// DONT FORGET TO ADD THE NEW COLUMN TO YOUR MODEL
NEW_COLUMN: {
type: DataTypes.STRING,
allowNull: true,
}
// ...
});
Employee.basicAttributes = (alias = 'employee') => [
'id',
'name',
'NEW_COLUMN',
// ...
];
const employee = await Employee.findOne({
where: { id: id },
attributes: Employee.basicAttributes(),
});
It's not ideal, but it works, and it doesn't require to run sequalize.sync({force:true})
.
Upvotes: 1
Reputation: 1787
you need to resync the table for changes to take effect try sequalize.sync({force:true})
hope it helps :)
Upvotes: 3