How to use milliseconds in sequelize standard createdAt field?

问题内容:

In a Nodejs application I’m using the Sequelize ORM to write records to a mysql database. Every table has a createdAt field by default, but that only records datetime with seconds:

mysql> SELECT createdAt FROM ticks LIMIT 3;
+---------------------+
| createdAt           |
+---------------------+
| 2017-11-08 16:34:21 |
| 2017-11-08 16:34:15 |
| 2017-11-08 16:34:27 |
+---------------------+
3 rows in set (0.00 sec)

Since I’m running a very time sensitive service I would also like to record milliseconds. In the docs I found the data types, which includes:

Sequelize.DATE(6)  // DATETIME(6) for mysql 5.6.4+. Fractional seconds support with up to 6 digits of precision

I never explicitly write the createdAt field though (Sequelize does that automagically), so I’m not sure how I could make that write milliseconds.

Could anybody point me in the right direction to save records with the createdAt field using millisecond precision? All tips are welcome!

问题评论:

答案:

答案1:

You can define createdAt explicitly in your model, for example:

id: {
    type: Sequlieze.INTEGER(11).UNSIGNED,
    autoIncrement: true,
    primaryKey: true
},
...
...
createdAt: {
    type: schema.DATE(6),
    allowNull: true,
    defaultValue: Sequelize.fn('NOW')
}

Or rename it by:

created_ts: {
    type: schema.DATE(6),
    allowNull: true,
    defaultValue: Sequelize.fn('NOW')
}, {
    createdAt: created_ts
}

答案评论:

原文地址:

https://stackoverflow.com/questions/47752672/how-to-use-milliseconds-in-sequelize-standard-createdat-field

添加评论

友情链接:蝴蝶教程