使用Postman调用API获取家庭设备返回空对象{}问题排查
问题描述
我在MongoDB中创建了Families、Users、Devices三类文档,期望通过HTTP请求中的familyId参数(示例请求:http://localhost:8567/get?familyId=65f1dcc828d6b2d79bb2f4b4)获取指定家庭下的所有设备。但使用Postman调用接口时返回空对象{},单独返回familyId可正常执行,却无法返回Devices模型中的设备数据。
Families模型
const mongoose = require('mongoose'); const FamiliesSchema = new mongoose.Schema({ address: String, name: String, users: [{ type: mongoose.Schema.Types.ObjectId, ref:'Users' }], devices: [{ type: mongoose.Schema.Types.ObjectId, ref:'Devices' }] }, { collection:'Families' } ); let Families = mongoose.model('Families', FamiliesSchema); module.exports = {Families};
Users模型
const mongoose = require('mongoose'); const UsersSchema = new mongoose.Schema({ name: String, age: Number, devices: [{ type: mongoose.Schema.Types.ObjectId, ref:'Devices' }], }, { collection: 'Users' } ); let Users = mongoose.model('Users', UsersSchema); module.exports={Users};
Devices模型
const mongoose = require('mongoose'); const DevicesSchema = new mongoose.Schema({ name: String, }, { collection: 'Devices' } ); let Devices = mongoose.model('Devices', DevicesSchema); module.exports = {Devices};
Express路由定义
const router = require('express').Router(); const DevicesControl = require('../Controller/DevicesController'); // GET router.get('/get', DevicesControl.getFamilyDevices); module.exports = router;
控制器代码
const mongoose = require('mongoose'); const Devices = require('../HomeModel/Devices'); const Families = require('../HomeModel/Families'); const ObjectId = mongoose.Types.ObjectId const DevicesControl = { getFamilyDevices: async (req, res) => { try { console.log('GET request is active'); const familyId = req.query.familyId; if (!familyId) { res.status(404).json('Family not found'); } const foundFamily = await Families.findById(familyId); const devices = await foundFamily.devices() res.status(200).json(devices); } catch (error) { res.status(500).json({ error: 'Error getting Devices', details: error }); } } }; module.exports = DevicesControl;
问题原因分析
- 错误调用引用字段:
foundFamily.devices是存储设备ObjectId的数组,不是方法,加()调用属于语法错误。 - 未填充引用数据:仅用
findById查询Families,只会返回设备的ObjectId数组,不会自动关联获取Devices模型的具体数据,需要用Mongoose的populate方法填充。 - 边界处理缺失:当
familyId对应家庭不存在时,foundFamily会为null,后续代码会触发报错,但当前逻辑未处理该情况。
修复方案
修改控制器中的getFamilyDevices方法:
const mongoose = require('mongoose'); const Devices = require('../HomeModel/Devices'); const Families = require('../HomeModel/Families'); const ObjectId = mongoose.Types.ObjectId const DevicesControl = { getFamilyDevices: async (req, res) => { try { console.log('GET request is active'); const familyId = req.query.familyId; if (!familyId) { return res.status(400).json('FamilyId parameter is required'); } // 用populate填充devices字段,获取完整设备数据 const foundFamily = await Families.findById(familyId).populate('devices'); if (!foundFamily) { return res.status(404).json('Family not found'); } // 直接返回填充后的设备数组 res.status(200).json(foundFamily.devices); } catch (error) { res.status(500).json({ error: 'Error getting Devices', details: error.message }); } } }; module.exports = DevicesControl;
关键修复点说明
- 添加
populate('devices'):查询家庭时自动关联Devices模型,将ObjectId替换为完整的设备文档。 - 修正字段调用方式:移除
foundFamily.devices()的括号,直接访问foundFamily.devices属性。 - 完善校验逻辑:
familyId为空时返回400(参数错误),语义更准确;- 检查
foundFamily是否存在,不存在时返回404。
- 优化错误信息:返回
error.message让错误内容更清晰。
内容的提问来源于stack exchange,提问作者stanps7
相关产品推荐
相关产品推荐

