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

Node.js新手求助:MongoDB GET接口查询异常排查

问题排查与修复建议

Hey there! Let's break down the issues in your Node.js GET endpoint and fix them step by step:

核心问题分析

  • 错误的状态码使用:当缺少id参数时,你返回了500(服务器内部错误),但这属于客户端请求错误,应该用400 Bad Request更符合HTTP规范。
  • 不完整的响应逻辑:
    • 你的findOne回调只处理了err情况,完全没处理找到文档或者未找到文档的场景,会导致客户端请求一直挂起直到超时。
    • 错误场景下只调用了res.end("N..."),没有设置错误状态码,客户端无法正确识别这是错误响应。
  • 代码冗余:参数检查后的res.end()加return可以优化为提前返回,让代码更简洁易读。

修复后的代码示例

router.get('/EPODS/Product/:id?', function(req, res) {
    // 检查id参数是否存在,不存在则返回400错误
    if(!req.params.id){
        return res.status(400).json({ 
            "Error": "Product ID is required. Please provide a valid ID and check for case sensitivity in input fields." 
        });
    }

    const inputIdObj = {'ProductEBM.DataArea.Product.ProductGroupID': req.params.id};

    db.collection('Product').findOne(inputIdObj,function(err, doc) {
        if (err) {
            console.error("Database query error:", err);
            // 数据库错误返回500状态码
            return res.status(500).json({ "Error": "Failed to fetch product data" });
        }

        if(!doc){
            // 未找到文档返回404状态码
            console.log("No record found for the given ID:", req.params.id);
            return res.status(404).json({ "Error": "No product found with the provided ID" });
        }

        // 成功找到文档,返回数据
        res.json(doc);
    });
});

额外优化建议

  • 使用async/await替代回调函数,让异步逻辑更线性易读(需要把路由处理函数改成async):
router.get('/EPODS/Product/:id?', async function(req, res) {
    if(!req.params.id){
        return res.status(400).json({ 
            "Error": "Product ID is required. Please provide a valid ID and check for case sensitivity in input fields." 
        });
    }

    try {
        const inputIdObj = {'ProductEBM.DataArea.Product.ProductGroupID': req.params.id};
        const doc = await db.collection('Product').findOne(inputIdObj);
        
        if(!doc){
            console.log("No record found for the given ID:", req.params.id);
            return res.status(404).json({ "Error": "No product found with the provided ID" });
        }

        res.json(doc);
    } catch(err) {
        console.error("Database query error:", err);
        res.status(500).json({ "Error": "Failed to fetch product data" });
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:22:20