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.
const TODAY = new Date(); const SUM = await OrdersModel. sum('price', { where: { created: Sequelize. DATE(TODAY), }, }); console. log(SUM);
When you create a Sequelize model, you can add the default value for your model by adding the defaultValue option to the column(s) definition. The defaultValue option will be used by Sequelize to define default value(s) for your SQL column(s) when you create a table using Sequelize.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With