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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:30:54