首页 > 解决方案 > 记录不会使用 Nestjs 和 TypeOrm 保存到数据库(查询有效)

问题描述

当我发布请求时,它不会将我的实体保存到数据库中,也不会报告任何错误或警告。

控制器:

@Controller('recipes')

export class RecipesController {
  constructor(private readonly recipeService: RecipesService) {}
  @Get()
  async findAll(): Promise<Recipe[]> {
    return this.recipeService.findAll();
  }

  @Post()
  async create(@Body() createRecipeDto: Recipe) {
    this.recipeService.create(createRecipeDto);
  }
}

服务:

@Injectable()
export class RecipesService {
    constructor(@InjectRepository(Recipe) private readonly recipeRepository: Repository<Recipe>) {}

    async create(recipe: Recipe) {
        const d = await this.recipeRepository.create(recipe);
        console.log("d:", d);
    }

    async findAll() {
        return await this.recipeRepository.find();
    }
}

实体:

@Entity()
export class Recipe {
  @PrimaryGeneratedColumn()
  id: number;

  //   @IsString()
  @Column()
  name: string;

  //   @IsString()
  @Column('text')
  description?: string;

  //   @IsString()
  @Column()
  image: string;

  //   @IsArray()
  ingredients: string[];

  //   @IsArray()
  instructions: string[];

  //   @IsString()
  @Column()
  prepTime?: string;

  //   @IsString()
  @Column()
  cookTime?: string;

  //   @IsString()
  @Column()
  yield?: string;

  //   @IsNumber()
  @Column('int')
  rating?: number;

  //   @IsArray()
  keywords?: string[];

  //   @IsArray()
  categories: string[];

  //   @IsString()
  @Column()
  cuisine?: string;

  //   @IsBoolean()
  @Column('boolean')
  draft?: boolean;
}

我使用邮递员的要求:

curl -X POST \
  http://localhost:3000/recipes \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: f23b5d42-1c40-4dae-b9b8-b32b733f38b4' \
  -H 'cache-control: no-cache' \
  -d '{
    "name":"recipe5",
    "description": "desc",
    "image": "http://..",
    "ingredients": ["-"],
    "instructions": ["1"],
    "prepTime": "1:20",
    "cookTime": "1:00",
    "yield": "8 servings",
    "rating": 4,
    "keywords": ["1"],
    "categories": ["cat1", "cat2"],
    "cuisine": "American",
    "draft": false
}'

它返回 201。我的 GET 调用仅返回我手动创建的条目。

标签: nestjstypeorm

解决方案


我发现了问题!

TypeOrm 的Repository.create实际上并没有将实体保存到存储中。为此,您必须调用Repository.save.

我的服务中的这种更改解决了我的问题:

从:

const d = await this.recipeRepository.create(recipe);

至:

const d = await this.recipeRepository.save(recipe);

推荐阅读