'Changing data type of 'createdAt' and 'updatedAt' fields in Sequelize model to DATE(6)
Sequelize automatically adds a createdAt and a updatedAt field for every model, both of which are set to type DATE by default. I want to update this to DATE(6) to be able to make use of millisecond timestamps. I have two questions regarding this:
- How do I go about creating a migration that enables this?
- If I update the datatype to
DATE(6), will the existing database records be unaffected and will only the newer ones have the millisecond timestamp?
Solution 1:[1]
1- The migration required to effect this change (presuming a cards table):
module.exports = {
up: (queryInterface, Sequelize) => {
return Promise.all([
// cards
queryInterface.changeColumn('cards', 'createdAt', {
type: Sequelize.DATE(6),
allowNull: true,
}),
queryInterface.changeColumn('cards', 'updatedAt', {
type: Sequelize.DATE(6),
allowNull: true,
}),
])
},
down: (queryInterface, Sequelize) => {
return Promise.all([
// cards
queryInterface.changeColumn('cards', 'createdAt', {
type: Sequelize.DATE,
allowNull: true,
}),
queryInterface.changeColumn('cards', 'updatedAt', {
type: Sequelize.DATE,
allowNull: true,
}),
])
}
};
2- The preceding migration runs an ALTER TABLE query on the cards table and all rows (previous ones and those that are yet to be inserted) will get the millisecond timestamp.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amer |
