Problem with updating record

#1

Hello !
I have problem with updating record. For example i have code like :

const resetPassword = await ResetPassword.findBy('token', token);
resetPassword.used = 1;
await resetPassword.save();

Above code should update my used field to 1 - but in my DB there is no changes :frowning:
Of course i can update using e.g.:

await ResetPassword.query().where('token', token).update({ used: 1 })

but I think this is not good solution.

PS. This is my schema:

this.create('reset_passwords', (table) => {
      table.uuid('id').primary()
      table.uuid('user_id').nullable()
      table.foreign('user_id')
        .references('id')
        .on('users')
        .onDelete('cascade')
      table.string('token', 255)
      table.boolean('used').default(0)
      table.timestamps()
    })

Thank You very much for help ! :slight_smile:

0 Likes

#2

Are you sure resetPassword is not null in:

const resetPassword = wait ResetPassword.findBy('token', token);

Run console.log(resetPassword) just after this line and see.

0 Likes

#3

Yes,

const resetPassword = await ResetPassword.findBy('token', token);

is not null. This is ResetPassword instance - even if I change used field, I see this value changed. Unfortunately after resetPassword.save() no changes are visible.

If resetPassword would be null, propably I would receive error if I would like execute save() function

0 Likes

#4

Hi, did you add any hook to the model?

0 Likes

#5

Hi ! :slight_smile: Yes, I have two hooks

ResetPasswordHook.setUuid = async resetPassword => resetPassword.id = await uuid.v4();
ResetPasswordHook.generateToken = async resetPassword => resetPassword.token = await randomString(50);

I added them in model class on boot() method:

this.addHook('beforeSave', 'ResetPasswordHook.setUuid');
this.addHook('beforeSave', 'ResetPasswordHook.generateToken');
0 Likes

#6

I think you should change the hook to beforeCreate since beforeSave will be trigger for create or update the model instance.
So, when you update your instance now will generate new id and token that expected update will not be success.:slightly_smiling_face:

FYI: https://adonisjs.com/docs/4.1/database-hooks#_lifecycle_events

1 Like

#7

Yeah ! You are right, now it works like a charm !
Thank you so much !

0 Likes