You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构造Postman GET请求通过MongoDB生成的_id获取对应数据条目

解决方案

1. 修复代码中的致命错误

你当前的findProduct方法存在变量重复声明的问题,导致查询到的商品永远不会被正确返回:

// 错误写法
private async findProduct(id: string): Promise<Product> {
    let product;
    try {
    // 这里又声明了一个局部的const product,外层的product永远是undefined
    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;
}

修正为:

private async findProduct(id: string): Promise<Product> {
    let product;
    try {
        product = await this.productModel.findById(id).exec(); // 去掉重复的const声明,加exec符合Mongoose调用规范
    } catch (error) {
        throw new NotFoundException('Product not found');
    }
    if (!product) {
        throw new NotFoundException('Product not found');
    }
    return product;
}

2. 修正返回字段的笔误

getSingleProduct方法中Color字段错误取了Price的值,属于业务逻辑bug,修正:

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.Color, // 原代码写为product.Price,此处修正
        isDeleted: product.isDeleted 
    };
}

3. Postman请求构造方法

你的Controller路由前缀是produse,所以请求格式如下:

  • 请求方式选GET
  • 请求URL填:http://<你的服务地址>:<服务端口>/produse/61a51cacdfb9ea1bd9395874
    示例:如果服务在本地运行、端口为3000,URL就是http://localhost:3000/produse/61a51cacdfb9ea1bd9395874
  • 不需要额外添加请求头或参数,直接点击发送即可获取对应商品数据。

额外注意事项

如果你的Mongoose模型没有配置_id到id的自动映射,需要将返回的id改为product._id.toString(),否则会出现id字段为空的问题。

内容的提问来源于stack exchange,提问作者Teodor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:15:04