所以我有一个案例,我想将一个对象作为 json 字符串保存到数据库中
但是每次都会收到错误和警告,因为模型被设置为字符串或对象
我需要两种不同的邮寄模式吗?或者有更优雅的方法来处理这类问题?
这就是我现在的编码方式
@Get("/")
@Summary("Return List Of blogs")
@Returns(200, Array)
async getAll(@QueryParams() blogFilter: any) {
return await this.service.findMany(blogFilter)
}
@Post("/")
@Summary("Create New Blog")
@Returns(201, BlogModel)
async create(@BodyParams() @Groups("creation") blog: BlogModel): Promise<BlogModel> {
// @ts-ignore
blog.content = JSON.stringify(await this.mediaService.contentMediaConvert(blog.content));
return await this.service.create(blog);
}
博客内容应该是来自前端的对象,但为空格保存为JSON字符串
这是我现在的模型
export class BlogModel {
@ObjectID("id")
_id: string;
@Property()
@Required()
@Lowercase()
title: string;
@Property()
@Lowercase()
slug: string;
@Property()
@Any()
content: object;
@Property()
@Ref(CategoryModel)
category: Ref<CategoryModel>
@Property()
@Default(0)
views: number;
@Property()
@Required()
@Ref(UserModel)
createdBy: Ref<UserModel>;
@Property()
@Required()
@Ref(MediaModel)
thumbnail: Ref<MediaModel>;
@Property()
@Default("BLOG")
@Enum(pageType)
pageType: pageType
}
我很讨厌面向对象对不起
问题不够清楚,无法理解问题。如果您还可以发布服务的错误消息和界面,那将会有所帮助。但我可以对我所看到的发表一些评论。
我需要两种不同的 post 和 get 模型吗
不,这不是必需的。您可以使用一种模型进行 POST 和 GET。
// @ts-ignore
blog.content = JSON.stringify(await this.mediaService.contentMediaConvert(blog.content));
return await this.service.create(blog);
问题可能来自
JSON.stringify
。 service.create
很有可能使用对象而不是字符串作为参数。所以,在理想情况下,这应该是this.service.create(await this.mediaService.contentMediaConvert(blog.content))
其他一些与您的问题无关的评论:
@QueryParams() blogFilter: any
。不要使用any
,尝试定义像class BlogFilterQuery
这样的东西
你不需要
await
return
尽量避免使用Json字符串。有一些模块可以帮助您在 JSON 和类实例之间进行转换。例如,
class-transfromer
.
希望这有帮助,