TypeORM @BeforeInsert not inserting value into Entity field

Viewed 454

i am trying to update or insert into a token field before the record is saved but when i use the @BeforeInsert hook, i get this error "error": "Cannot read property 'concat' of undefined" i clearly understand the error, but i dont get why it is happening because this.tokens is a property of the entity user class.

@Entity('users')
class User extends BaseEntity {
@Column({
    type: 'jsonb',
    array: false,
    default: () => "'[]'",
    nullable: false,
  })
  tokens!: Array<{ token: string }>;
}

@BeforeInsert()
  toJSON(): object {
    const user = this;
    user.tokens = user.tokens.concat({ token: "34e5trfkljhkhgufy42343567" });
    // user.save();
    user.resetlink = "https://www.google.com";
    console.log('second', user)
    return user;
  };

and when i use the afterinsert hook it works but the token get assigned twice, which is not what i want.

@AfterInsert()
  toJSON(): object {
    const user = this;
    user.tokens = user.tokens.concat({ token: "34e5trfkljhkhgufy42343567" });
    // user.save();
    user.resetlink = "https://www.google.com";
    console.log('second', user)
    return user;
  };
1 Answers

In your column decorator, you are giving this entity a default value for the tokens field which is an empty list. When the BeforeInsert is called, this default value is not yet assigned and therefore tokens is actually undefined which is causing the error.

Not sure why the value would be assigned twice in AfterInsert, but my assumption is that you're calling this.save() which triggers another AfterInsert.

Related