Nest.js中TypeORM save方法无法自动生成@PrimaryGeneratedColumn ID问题
解决TypeORM @PrimaryGeneratedColumn自动生成ID失败问题
使用Nest.js + TypeORM开发时,通过@PrimaryGeneratedColumn()注解期望让主键ID自动生成,但调用save()方法时抛出错误:Field 'id' doesn't have a default value,手动指定ID可正常保存数据。相关代码如下:
post.dto.ts
import { IsString } from 'class-validator'; export class PostDto { @IsString() name: string; @IsString() content: string; @IsString() date: string; }
guestbook.entity.ts
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class Guestbook { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() content: string; @Column({type:'date'}) date: string; }
guestbook.controller.ts
import { Body, Controller, Get, Post } from '@nestjs/common'; import { GuestbookService } from './guestbook.service'; import { PostDto } from './dtos/post.dto'; @Controller('guestbook') export class GuestbookController { constructor(private guestbookService: GuestbookService) {} @Get() getAllPosts() { return this.guestbookService.getAllPosts(); } @Post() saveNewPost(@Body() body: PostDto) { return this.guestbookService.saveNewPost(body.name,body.content,body.date.slice(0,10)); } }
guestbook.service.ts
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Guestbook } from './guestbook.entity'; import { Repository } from 'typeorm'; @Injectable() export class GuestbookService { constructor( @InjectRepository(Guestbook) private repo: Repository<Guestbook>, ) {} getAllPosts() { return this.repo.find(); } saveNewPost(name: string, content: string, date: string) { const newPost = this.repo.create({ name, content, date }); return this.repo.save(newPost); } }
解决方案
1. 检查并修正数据库表结构
@PrimaryGeneratedColumn()默认会生成自增主键,但如果数据库中guestbook表的id字段未设置自增属性,就会导致报错。以MySQL为例,需要将id字段设置为:
- 类型:INT(或BIGINT)
- 主键:PRIMARY KEY
- 自增:AUTO_INCREMENT
可通过SQL语句修改:
ALTER TABLE guestbook MODIFY COLUMN id INT AUTO_INCREMENT PRIMARY KEY;
2. 开启TypeORM表结构同步(开发环境适用)
在Nest.js的TypeORM配置中,将synchronize设为true,让TypeORM自动根据实体类同步数据库表结构,确保id字段被正确配置为自增:
// app.module.ts 中的TypeORM配置 TypeOrmModule.forRoot({ // 其他配置... synchronize: true, // 开发环境开启,生产环境禁用 })
注意:生产环境禁止使用
synchronize: true,可能会导致数据丢失,建议使用TypeORM迁移脚本管理表结构变更。
3. 显式指定主键生成策略
在@PrimaryGeneratedColumn()中明确指定生成策略为increment,确保TypeORM使用自增逻辑,适配不同数据库:
// guestbook.entity.ts @PrimaryGeneratedColumn('increment') id: number;
配置完成后,TypeORM会自动为新插入的数据生成唯一自增ID,无需手动指定。
内容的提问来源于stack exchange,提问作者Benjamin
相关产品推荐
相关产品推荐

