Set defaultValue to todays date in a Sequelize migration
Solution 1
You need to use as a default value the MySQL function NOW()
.
So your column declaration should look like :
{
type: Sequelize.DATEONLY,
allowNull: false,
defaultValue: Sequelize.NOW
}
Keep in mind that this will not populate the fields in your migration. They will be empty, since they were not created with sequelize.
Solution 2
Sequelize.NOW
will work in future but some versions(I tried 4.43.0) seem not support it.
I succeeded in setting now()
with using Sequelize.fn('now')
.
{
type: Sequelize.DATEONLY,
allowNull: false,
defaultValue: Sequelize.fn('now')
}
Reference: https://github.com/sequelize/sequelize/issues/4679
Solution 3
https://github.com/sequelize/sequelize/issues/645#issuecomment-18461231
createdAt: {
field: 'created_at',
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
}
Solution 4
SQL Server users must use literal('CURRENT_TIMESTAMP')
createdAt: {
field: 'created_at',
type: DataTypes.DATE,
allowNull: false,
defaultValue: literal('CURRENT_TIMESTAMP'),
}
Solution 5
Use "literal", see below.
updated_at: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
}
Andreas
Updated on July 22, 2022Comments
-
Andreas almost 2 years
I'm using Node Express with Sequelize and I want to set the defaultValue for the column "date" in the database to todays date. I tried with the following migration, but it didn't work, as it set the default date to be the same date as when I ran the migration. I want it to be set to the same date as when the row is created.
module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.addColumn( 'Todos', 'date', { type: Sequelize.DATEONLY, allowNull: false, defaultValue: new Date() } ) },
I can't understand how that would work.