Home > Net >  Postman GET request in order to retrieve a Mongodb entry by _id
Postman GET request in order to retrieve a Mongodb entry by _id

Time:12-01

I'm trying to build a postman GET request in order to retrieve an entry that I have in a MongoDB by using the unique id generated in the database.

To be more precise, I am interested in writing a GET request to retrieve for example the next entry :

{
        "id": "61a51cacdfb9ea1bd9395874",
        "Name": "asdsd",
        "Code": "asdca",
        "Weight": 23,
        "Price": 23,
        "Color": "sfd",
        "isDeleted": false
    }

Does anyone have an idea how to include that id in the GET request in order to retrieve the prodcut from above?

Thanks!

EDIT :

@J.F thank you for the kind response and information provided, but unforunately, it still does not work :(.

Those are the products that I have right now, and I tried to GET the one with id = 61a51cacdfb9ea1bd9395874

example

And this is the response I got : enter image description here

Also, this is the logic that I implemented for the GET request :

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 };

CodePudding user response:

To implement a RESTful API your endpoints has to be like this:

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

The path you want is GET /resource/:id

The id is used into route because is unique and identify a resource.

So your path can be something like:

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