【发布时间】:2022-01-06 17:09:05
【问题描述】:
我正在尝试构建一个邮递员 GET 请求,以便使用数据库中生成的唯一 ID 检索我在 MongoDB 中的条目。
更准确地说,我有兴趣编写一个 GET 请求来检索例如下一个条目:
{
"id": "61a51cacdfb9ea1bd9395874",
"Name": "asdsd",
"Code": "asdca",
"Weight": 23,
"Price": 23,
"Color": "sfd",
"isDeleted": false
}
有谁知道如何在 GET 请求中包含该 id 以便从上面检索产品?
谢谢!
编辑:
@J.F 感谢您提供的友好回复和信息,但不幸的是,它仍然不起作用:(。
这些是我现在拥有的产品,我尝试获取 id = 61a51cacdfb9ea1bd9395874 的产品
另外,这是我为 GET 请求实现的逻辑:
filename : product.service.ts
async getSingleProduct(productId: string) {
const product = await this.findProduct(productId);
return {
id: product.id,
Name: product.Name,
Code: product.Code,
Weight: product.Weight,
Price: product.Price,
Color: product.Price,
isDeleted: product.isDeleted };
}
private async findProduct(id: string): Promise<Product> {
let product;
try {
const product = await this.productModel.findById(id)
} catch (error) {
throw new NotFoundException('Product not found');
}
if (!product) {
throw new NotFoundException('Product not found');
}
return product;
}
filename : product.controller.ts
@Get(':id')
getProduct(@Param('id') prodId: string) {
return this.productsService.getSingleProduct(prodId)
}
EDIT2:
@Controller('produse')
export class ProductsController {
constructor(private readonly productsService: ProductsService) {}
@Post()
async addProduct(
@Body('Name') prodName: string,
@Body('Code') prodCode: string,
@Body('Weight') prodWeight: number,
@Body('Price') prodPrice: number,
@Body('Color') prodColor: string,
@Body('isDeleted') prodIsDeleted: boolean,
) {
const generatedId = await this.productsService.createProduct(
prodName,
prodCode,
prodWeight,
prodPrice,
prodColor,
prodIsDeleted
);
return { id: generatedId };
【问题讨论】:
标签: mongodb get request postman