设置item.videoProgress后最终返回的document对象无该字段如何解决
问题原因
你通过Mongoose查询得到的documentList中的每一项都是Mongoose Document实例,不是原生JavaScript对象,这类实例默认禁止挂载未在Schema中定义的自定义字段,序列化返回时会自动过滤掉未声明的字段,这就是你手动赋值videoProgress后响应里拿不到的核心原因。
解决方案
方案1:查询时添加lean()方法(最推荐)
在查询documentList的语句末尾加上.lean(),查询结果会直接返回原生JS对象,不需要改动后续处理逻辑,直接给item.videoProgress赋值就会生效:
// 仅需要修改你原有查询documentList的代码,示例: const documentList = await 你的Model.find(查询条件).lean();
方案2:处理前将Document实例转为原生对象
如果不能修改原查询语句,可以在处理每一项的时候用toObject()方法转成原生对象后再赋值,修改后的代码如下:
const document = await Promise.all(documentList.map(async (item) => { const videoCount = await studentProgressModel.find({ gradeId: item.gradeId, userId : item._id, type: 'VIDEO'}).countDocuments(); const totalVideoCount = await videoModel.find({ gradeId: item.gradeId, mediumId: item.mediumId, status: 'ACTIVE' }).countDocuments(); let videoPercentage = 0; if(totalVideoCount > 0) { videoPercentage = (100 * videoCount) / totalVideoCount; } // 转成原生JS对象后再赋值自定义字段 const plainItem = item.toObject(); plainItem.videoProgress = videoPercentage; return plainItem; }));
方案3:Schema中显式声明字段
如果需要在Mongoose实例上长期使用这个字段,可以在对应的Schema中添加videoProgress字段定义,不需要存库的话可以设置为虚拟字段:
const yourSchema = new mongoose.Schema({ // 原有字段定义 }) // 虚拟字段不会持久化到数据库,仅运行时可用 yourSchema.virtual('videoProgress').get(function() { return this._videoProgress; }).set(function(val) { this._videoProgress = val; })
内容的提问来源于stack exchange,提问作者user7515288
相关产品推荐
相关产品推荐

