Node.js中无法为MongoDB查询结果JSON对象添加属性的问题
问题原因
Mongoose查询返回的data是Mongoose Document对象,并非普通JavaScript对象。这类对象有自身的内部结构与属性访问控制逻辑,它的属性基于Schema定义,直接新增的额外属性不会被默认识别和显示。
解决方法
方法1:将Document转为普通JS对象
获取data后调用toObject()方法,把Mongoose文档对象转换成普通JS对象,之后再添加属性即可正常生效:
const getLessonWithTopics = async (req, res) => { const lessonId = req.params.id; Lesson.findOne({_id: lessonId}).exec((err, data) => { if (err) return res.status(500).send("Error something went wrong"); // 转换为普通JS对象 let lesson = data.toObject(); Topic.find().where('_id').in(data.topics).exec((err, topics) => { if(err) return res.status(500).send("Error something went wrong"); lesson.associatedTopics = topics; console.log(lesson); res.json(lesson) }) }) }
方法2:使用lean()查询直接返回普通对象
在查询时添加lean()选项,Mongoose会直接返回普通JS对象,无需额外转换:
const getLessonWithTopics = async (req, res) => { const lessonId = req.params.id; // 添加lean(),直接获取普通对象 Lesson.findOne({_id: lessonId}).lean().exec((err, data) => { if (err) return res.status(500).send("Error something went wrong"); let lesson = data; Topic.find().where('_id').in(data.topics).exec((err, topics) => { if(err) return res.status(500).send("Error something went wrong"); lesson.associatedTopics = topics; console.log(lesson); res.json(lesson) }) }) }
额外优化:改用async/await避免回调地狱
既然函数已声明为async,建议用async/await写法,代码逻辑更清晰,错误处理更统一:
const getLessonWithTopics = async (req, res) => { try { const lessonId = req.params.id; // 用lean()直接获取普通对象 const lesson = await Lesson.findOne({_id: lessonId}).lean(); const topics = await Topic.find().where('_id').in(lesson.topics); lesson.associatedTopics = topics; console.log(lesson); res.json(lesson); } catch (err) { res.status(500).send("Error something went wrong"); } }
内容的提问来源于stack exchange,提问作者Will 40
相关产品推荐
相关产品推荐

