TypeORM在Nest.js中使用queryBuilder插入后引发错误



我有一个实体和服务定义如下。

  1. user.entity.js
@Entity({ name: 'users' })
export class User {
@Column({
type: 'binary',
length: 16,
select: false,
primary: true,
default: () => `(UUID_TO_BIN(UUID(), 1))`,
})
id: string;
@Index()
@Column({ type: 'varchar', length: 225, nullable: false })
name: string;
@Column({ type: 'varchar', length: 15, unique: true, nullable: false })
MSISDN: string;
@Column({ type: 'varchar', length: 225, unique: true, nullable: false })
email_address: string;
@Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' })
created_at: Date;
@Column({ type: 'datetime', nullable: true, onUpdate: 'CURRENT_TIMESTAMP' })
updated_at: Date;
}
  1. user.service.js
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
create(user: DeepPartial<User>): Promise<User> {
return this.usersRepository
.createQueryBuilder()
.insert()
.values({ ...user})
.execute();
}
}

每当我试图从Postman客户端创建用户时,记录实际上都会插入数据库中,但我从Postman客户端得到500的响应。

邮差回复

{
"statusCode": 500,
"message": "Internal server error"
}

CLI错误如下所示:

[Nest] 9084   - 15/03/2021, 11:17:47   [ExceptionsHandler] Cannot update entity because entity id is not set in the entity. +331142ms
Error: Cannot update entity because entity id is not set in the entity.
at C:UsersMnengwaworkspacekodishakodisha-web-apinode_modulestypeormquery-builderReturningResultsEntityUpdator.js:128:39
at Array.map (<anonymous>)
at ReturningResultsEntityUpdator.<anonymous> (C:UsersMnengwaworkspacekodishakodisha-web-apinode_modulestypeormquery-builderReturningResultsEntityUpdator.js:122:46)
at step (C:UsersMnengwaworkspacekodishakodisha-web-apinode_modulestypeormnode_modulestslibtslib.js:141:27)
at Object.next (C:UsersMnengwaworkspacekodishakodisha-web-apinode_modulestypeormnode_modulestslibtslib.js:122:57)
at C:UsersMnengwaworkspacekodishakodisha-web-apinode_modulestypeormnode_modulestslibtslib.js:115:75
at new Promise (<anonymous>)
at Object.__awaiter (C:UsersMnengwaworkspacekodishakodisha-web-apinode_modulestypeormnode_modulestslibtslib.js:111:16)
at ReturningResultsEntityUpdator.insert (C:UsersMnengwaworkspacekodishakodisha-web-apinode_modulestypeormquery-builderReturningResultsEntityUpdator.js:87:24)
at InsertQueryBuilder.<anonymous> (C:UsersMnengwaworkspacekodishakodisha-web-apinode_modulestypeormquery-builderInsertQueryBuilder.js:105:76)

我不得不在save调用中将reload选项指定为false(而不是insert(以消除错误。

对于insert,您希望在调用execute之前将updateEntity(false)调用添加到链中。

这里有更多的上下文:https://github.com/typeorm/typeorm/issues/4651

尝试如下定义User实体的id属性-

@PrimaryColumn()
@Generated('uuid')
id: string;

相关内容

  • 没有找到相关文章

最新更新