如何在Node.js中通过GET方法从MongoDB获取指定城市的数据?
问题分析与修复方案
核心问题
- 查询逻辑错误:你在
/:city_name路由中使用schema.findById(city_name_code),但city_name_code是城市名称,并非MongoDB文档的_id字段,导致查询无法匹配数据;同时若请求路径未携带城市参数,会触发根路径的GET /接口,返回{"message": "get is working!"}。 - 请求路径可能不正确:路由挂载在
/hostdetails下,按城市查询的请求URL必须包含城市名称参数,否则会匹配根路由。
修复步骤
1. 修正查询逻辑
将findById替换为按City字段查询,根据需求选择返回单条或多条数据:
router.get("/:city_name", (req, res, next)=>{ const cityName = req.params.city_name; // 查询该城市的所有匹配数据 schema.find({ City: cityName }).exec() .then(docs=>{ console.log(docs); if(docs.length > 0){ res.status(200).json(docs); } else { res.status(404).json({ message: "未找到该城市的数据" }); } }) .catch(err=>{ console.log(err); res.status(500).json({error: err}); }); });
2. 确保请求路径正确
在Postman中发送GET请求时,URL必须包含城市名称参数,示例:
GET http://localhost:3000/hostdetails/Shanghai
替换为你的服务实际域名/端口和目标城市名。
3. 优化POST接口异步逻辑(可选)
原POST接口在数据未完成保存时就返回响应,可调整为异步等待保存完成:
router.post('/', async (req, res, next)=>{ try { const host = new schema({ _id: new mongoose.Types.ObjectId(), First_Name: req.body.f_name, Last_Name: req.body.l_name, State: req.body.state, City: req.body.city, Street_Address: req.body.st_address, Postal_Code: req.body.postal, Model_Make: req.body.model, Price: req.body.price, Lat: req.body.lat, Lng: req.body.lng }); const result = await host.save(); console.log(result); res.status(201).json({ message: '数据保存成功', createdHost: result }); } catch(err) { console.log(err); res.status(500).json({error: err}); } });
4. 添加数据库连接状态检查(可选)
在App.js中补充MongoDB连接的状态回调,确保连接正常:
mongoose.connect('mongodb+srv://xxx:xxxxxxxxxxxxxxxx.mt4xvth.mongodb.net/?retryWrites=true&w=majority&appName=xxxxxxxxxxxxxxx') .then(() => console.log("MongoDB连接成功")) .catch(err => console.log("MongoDB连接失败:", err));
验证
重启服务后,在Postman中发送带城市参数的GET请求,即可返回该城市对应的所有数据;若城市不存在,会返回404提示。
内容的提问来源于stack exchange,提问作者Driver
相关产品推荐
相关产品推荐

