Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid created_at and updated_at being auto generated by sequelize

Tags:

How do I define a model for which created_at and updated_at are provided rather than generated?

I'm importing data from somewhere that already has data for created_at and updated_at fields that I would like to preserve rather than generating whenever the object is created/updated by sequelize (our secondary store).

I've tried every likely permutation of model definition and options to get this to work and still sequelize overwrites my fields with it's own timestamps: {silent: true}, etc...

To be clear, the input data has createdAt and updatedAt and I'd like to use sequelize's bulkCreate(), etc such that input values provided are used and stored on the model as created_at and updated_at rather than generated by sequelize.

This is my current model definition:

const Lead = sequelize.define('lead', {   objectId: {     type: Sequelize.STRING,     field: 'objectId',     primaryKey: true,     allowNull: false   },   firstName: {     type: Sequelize.STRING,     field: 'first_name'   },   lastName: {     type: Sequelize.STRING,     field: 'last_name'   },   phoneNumber: {     type: Sequelize.STRING,     field: 'phone_number'   },   createdAt: {     type: Sequelize.DATE,     field: 'created_at',   },   updatedAt: {     type: Sequelize.DATE,     field: 'updated_at'   } }, {   freezeTableName: true, // Model tableName will be the same as the model name   timestamps: false,   underscored: true }); 
like image 934
Tyler Brock Avatar asked Apr 28 '16 06:04

Tyler Brock


People also ask

How do you prevent createdAt and updatedAt in Sequelize?

With timestamps: false , the generated model will omit the createdAt and updatedAt attributes. You can also opt to include only the timestamp attribute you need as shown below: const User = sequelize. define( "User", { firstName: Sequelize.

What does sync do Sequelize?

User.sync({ alter: true }) - This checks what is the current state of the table in the database (which columns it has, what are their data types, etc), and then performs the necessary changes in the table to make it match the model.


1 Answers

The option is

timestamps: false, 

Where timestamps is written fully lowercase

Update:

From looking at the code of the bulkCreate() function, it looks that it always updates the timestamps, so, without a patch this is not possible right now

like image 193
Tudor Constantin Avatar answered Sep 28 '22 13:09

Tudor Constantin