获取Post数据时无法返回array类型的comment与like字段,数据库中存在该字段
问题:获取Post数据时无法返回数据库中存在的数组字段
在获取Post的Schema数据时,接口响应里无法获取到comment和like这两个数组类型的字段,但这两个字段在数据库中确实存在。
我的Post获取代码
const post_modal = require("../../modals/post_model/postModel"); exports.fetchpost_control = async (req, res) => { try { const response = await post_modal.find().populate("comment").exec(); res.json({response}); } catch (e) { res.status(500).send({ success: false, data: e.message, message: "Internal server error" }); } };
数据库状态

接口响应情况

解决方案
检查Post Schema定义
确保你的Post模型Schema中已经正确声明了comment和like字段为数组类型,且未设置select: false(默认不设置就是返回该字段)。示例:const mongoose = require('mongoose'); const postSchema = new mongoose.Schema({ // 其他字段... comment: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }], // 关联Comment模型 like: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }] // 关联User模型,根据实际情况调整 }); module.exports = mongoose.model('Post', postSchema);Mongoose只会返回Schema中定义的字段,即使数据库里存在未定义的字段,查询结果也不会包含它们。
显式指定返回字段
如果Schema已正确定义但仍未返回,可在查询时显式指定要包含的字段:const response = await post_modal.find() .select('comment like') // 可追加其他需要返回的字段,比如title、content等 .populate("comment") .exec();验证populate配置
如果comment是关联其他集合的ObjectId数组,确保populate的参数与Schema中ref指定的模型名一致,否则填充会失败,但至少应该返回原始的ObjectId数组,而非完全缺失字段。
内容的提问来源于stack exchange,提问作者Ravi singh
相关产品推荐
相关产品推荐

