我正在使用Nest Serialization来转换api的响应。然而,它返回的结果非常神秘。我希望它能从数据中切出一些字段,但由于某些原因,它显示了奇怪的结果。
product.entity.js
export class ProductEntity {
id: string
description: string
status: boolean
price: string
moq: number
rating: number
last_modified: string
constructor(partial: Partial<ProductEntity>) {
Object.assign(this, partial)
}
}product.controller.ts
@UseInterceptors(ClassSerializerInterceptor)
@Get()
async findAll(
@Query('page') page: number,
@Query('per_page') per_page: number
): Promise<ProductEntity[]> {
if (!page && !per_page) {
throw new BadRequestException('Proper query params not supplied')
}
const data: ProductEntity[] = []
const products: any = await this.productService.findAll({
page,
per_page
})
products.map(product => {
data.push(new ProductEntity(product))
})
return data
}product.service.ts
async findAll(query): Promise<Product[]> {
const { page, per_page }: { page: number; per_page: number } = query
const from: number = (page - 1) * per_page
return this.productModel
.find()
.skip(from)
.limit(Number(per_page))
}它返回,
"$__": {
"strictMode": true,
"selected": {},
"getters": {},
"_id": {
"_bsontype": "ObjectID",
"id": {
"type": "Buffer",
"data": [
93,
15,
149,
140,
78,
148,
77,
10,
10,
105,
51,
130
]
}
},
"wasPopulated": false,
"activePaths": {
"paths": {
"moq_type": "init",
"moq": "init",
"price_type": "init",
"price": "init",
"name": "init",
"category_id": "init",
"company_id": "init",
"short_description": "init",
"long_description": "init",
"active": "init",
"variations": "init",
"keywords": "init",
"photos": "init",
"_id": "init",
"created_at": "init",
"updated_at": "init",
"__v": "init"
},
"states": {
"ignore": {},
"default": {},
"init": {
"_id": true,
"short_description": true,
"long_description": true,
"active": true,
"variations": true,
"keywords": true,
"photos": true,
"name": true,
"price": true,
"price_type": true,
"moq": true,
"moq_type": true,
"category_id": true,
"company_id": true,
"created_at": true,
"updated_at": true,
"__v": true
},
"modify": {},
"require": {}
},
"stateNames": [
"require",
"modify",
"init",
"default",
"ignore"
]
},
"pathsToScopes": {},
"cachedRequired": {},
"session": null,
"$setCalled": [],
"emitter": {
"_events": {},
"_eventsCount": 0,
"_maxListeners": 0
},
"$options": {
"skipId": true,
"isNew": false,
"willInit": true
}
},是我做错了什么,还是转换API响应的方式不正确?
发布于 2019-07-10 23:02:03
不确定NestJS,但在mongodb的常规node.js中,如果您以那种方式调用find() X().X().X(),则需要在管道的末尾添加对exec()方法的调用,如下所示:
this.productModel
.find()
.skip(from)
.limit(Number(per_page))
.exec();发布于 2019-12-29 01:20:55
我也明白这一点。答案是在您的控制器中删除@UseInterceptors(ClassSerializerInterceptor)。
也许该函数利用了类扩展中的对象继承?我认为您并不真正需要它,因为该函数用于转换响应(如将camerCase转换为snake_case等)。如果你真的需要它,那我就不知道了,因为我还在纠结于它。
https://stackoverflow.com/questions/56973423
复制相似问题