Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set defaultValue to todays date in a Sequelize migration

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.

like image 890
Andreas Avatar asked Nov 19 '16 15:11

Andreas


People also ask

How do you get the current date in Sequelize?

const TODAY = new Date(); const SUM = await OrdersModel. sum('price', { where: { created: Sequelize. DATE(TODAY), }, }); console. log(SUM);

How do I set default value in Sequelize migration?

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.


2 Answers

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.

like image 55
drinchev Avatar answered Nov 04 '22 02:11

drinchev


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

like image 43
asukiaaa Avatar answered Nov 04 '22 03:11

asukiaaa