使用Nestjs和TypeOrm记录不会保存到数据库(查询工作)

问题描述 投票:1回答:1

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

控制器:

@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;
}

我使用Postman的请求:

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调用仅返回我手动创建的条目。

nestjs typeorm
1个回答
3
投票

我发现了这个问题!

TypeOrm的Repository.create实际上并不将实体保存到存储中。要做到这一点,你必须打电话给Repository.save

我的服务中的这一变化解决了我的问题:

从:

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

至:

const d = await this.recipeRepository.save(recipe);
© www.soinside.com 2019 - 2024. All rights reserved.