Consider this entity:
// account.ts
import { Entity, PrimaryGeneratedColumn, PrimaryColumn, Column, BaseEntity, Index, CreateDateColumn, UpdateDateColumn, OneToOne, JoinColumn } from 'typeorm'
@Entity()
export class Account extends BaseEntity {
@PrimaryGeneratedColumn()
id: number
@Column({ length: 50, unique: true })
@Index({ unique: true })
accountIdentifier: string
@Column({ nullable: true, length: 100 })
name?: string
}
To save a new account or return an existing account we have this working code:
const knownAccount = await Account.findOne({ accountIdentifier: token.oid })
if (knownAccount) return done(null, knownAccount, token)
const account = new Account()
account.accountIdentifier = token.oid
account.name = token.name
account.userName = (token as any).preferred_username
const newAccount = await account.save()
return done(null, newAccount, token)
In the docs it says:
save - Saves a given entity or array of entities. If the entity already exist in the database, it is updated. If the entity does not exist in the database, it is inserted. It saves all given entities in a single transaction (in the case of entity, manager is not transactional). Also supports partial updating since all undefined properties are skipped. Returns the saved entity/entities.
So we would expect this code to work and replace the previous code but it does not seem to update the row but rather complains about inserting a duplicate key:
const account = await Account.save({
accountIdentifier = token.oid,
name = token.name,
userName = (token as any).preferred_username,
})
return done(null, account, token)
The IDE does show it will update or insert but it does not update:

How is it possible to use the save method correctly? So it adds an account if it doesn't exist and/or updates the account when it's already there.