Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of createdAt in Sequelize?

I would like to set the value of createdAt to some time in the past.

However, all of my attempts fail to change the createdAt date in the database. The value remains the same.

const yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);

// failed attempts
hang.createAt = yesterday;
hang.set('createdAt', yesterday);
hang.changed('createdAt', yesterday);

await hang.save();

I also tried

const yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);

// failed attempt
await hang.update({ createdAt: yesterday });

Proof of issue

2020-10-07T19:24:29.058Z // before
2020-10-07T19:24:29.058Z // after

How can I change the createdAt value of an instance?

like image 469
sgarza62 Avatar asked Oct 07 '20 19:10

sgarza62


1 Answers

try this

const yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);

hang.changed('createdAt', true);
hang.set('createdAt', yesterday,{raw: true});
await hang.save({
        silent: true,
        fields: ['createdAt']
 });    

from the documentation
set :

raw: true

if a custom setter function is defined for the key, that function will be called instead. To bypass the setter, you can pass raw: true in the options object.

and save :

  silent: true

If true, the updatedAt timestamp will not be updated.

like image 183
Tawfik Nasser Avatar answered Sep 21 '22 02:09

Tawfik Nasser