nestjs - 记录不会使用 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 调用仅返回我手动创建的条目。
解决方案
我发现了问题!
TypeOrm 的Repository.create实际上并没有将实体保存到存储中。为此,您必须调用Repository.save
.
我的服务中的这种更改解决了我的问题:
从:
const d = await this.recipeRepository.create(recipe);
至:
const d = await this.recipeRepository.save(recipe);
推荐阅读
- java - 是否可以在 Saxon 中缓存 XML 文档以避免重新解析和重新索引?
- android - CrashlyticsInitProvider 跳过初始化
- javascript - 如何在 javascript 代码中找到问题
- jquery - jQuery包装每个类+类元素(不同的类)
- javascript - 当另一个图像落在其上时如何防止图像消失
- jquery - 如何在 Angular 8 中添加 jqxEditorModule
- r - 从字符串中分离数字或字母数字数据
- typescript - 如何在角度 6 中获取对象子值
- php - laravel项目中的多重认证问题
- python-3.x - 为什么我会收到“ModuleNotFoundError: No module named 'Image'”错误?