gpt4 book ai didi

javascript - TypeOrm 保存方法不更新对象

转载 作者:行者123 更新时间:2023-12-04 15:21:12 24 4
gpt4 key购买 nike

考虑这个实体:

// 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
}
保存新 account或返回现有的 account我们有这个工作代码:
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)
the docs它说:

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.


所以我们希望这段代码能够工作并替换以前的代码,但它似乎没有更新行,而是提示插入重复键:
const account = await Account.save({
accountIdentifier = token.oid,
name = token.name,
userName = (token as any).preferred_username,
})
return done(null, account, token)
IDE 确实显示它将更新或插入但它不更新:
enter image description here
如何使用 save方法正确吗?因此,如果它不存在,它会添加一个帐户和/或在它已经存在时更新该帐户。

最佳答案

如果它可以帮助面临同样问题的人,我认为.save()如果主列(在本例中为 id)精确并存在于数据库中,则将执行更新。但是要小心,如果“id”的值是一个字符串,我不知道为什么,但不知何故,save 方法不会执行更新,而是会尝试在数据库中插入一个具有给定 id 的新实体,这可能如果 id 已经存在,则执行约束失败错误( duplicate entry '' for key 'PRIMARY' ),以避免将“id”简单地类型转换为整数。

关于javascript - TypeOrm 保存方法不更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63296895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com