【问题标题】:Postman GET request in order to retrieve a Mongodb entry by _idPostman GET 请求以通过 _id 检索 Mongodb 条目
【发布时间】: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


    【解决方案1】:

    要实现 RESTful API,您的端点必须是这样的:

    Verb Path
    GET /resource
    GET /resource/:id
    POST /resource
    PUT /resource/:id
    DELETE /resource/:id

    你想要的路径是 GET /resource/:id

    id 用于路由,因为它是唯一的并且标识资源。

    所以你的路径可以是这样的:

    http://localhost:8080/v1/resource/61a51cacdfb9ea1bd9395874
    

    【讨论】:

    • 感谢您的友好回复,但问题仍然存在 :(。您能检查我的更新信息吗?谢谢!
    • 不要在查询中使用:
    • 也试过没有':',但没有运气...... :(
    • 我明天会尝试重现代码并检查它失败的地方。另外请问您的路线是如何声明的?
    • 我已将其添加到 @ EDIT2。非常感谢 !如果您还需要什么,请告诉我
    猜你喜欢
    • 2016-07-03
    • 2021-06-24
    • 2016-11-21
    • 2023-03-16
    • 2015-10-01
    • 2020-07-29
    • 2021-12-31
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多