如何在Mongoose中嵌套填充fileInfo内的createdBy字段
解决Mongoose嵌套填充问题:填充Attachment的createdBy字段
问题分析
你需要从Document模型出发,先填充关联的Attachment(fileInfo字段),再进一步填充Attachment里的createdBy关联的User模型。原代码的问题在于:
User.populate的路径错误,此时documentView.fileInfo已经是Attachment实例,路径应该直接写createdBy而非fileInfo.createdBy- 没有处理
populate的异步特性,直接同步打印无法获取填充后的结果
方法一:使用Mongoose链式嵌套填充(推荐)
直接在查询阶段通过嵌套的populate配置完成多层填充,代码更简洁且无需额外处理异步:
Document.findOne({ _id: new mongoose.Types.ObjectId(documentId) }) .populate([ 'labels', { path: 'fileInfo', populate: { path: 'createdBy', model: 'User', // 可选:指定要返回的字段,匹配你期望的结果结构 select: 'name isSupportUser isActivated isSubscribed activateBttnClickCount primarySupport' } } ]) .then(function (documentView) { console.log(documentView, 'documentView'); return next(null, documentView); }) .catch(err => next(err)); // 补充错误处理
方法二:修复原有的分步填充代码
如果需要分步处理,要修正路径并处理异步:
Document.findOne({ _id: new mongoose.Types.ObjectId(documentId) }) .populate(['labels', 'fileInfo']) .then(async function (documentView) { // 修正路径:操作对象是fileInfo,直接指定createdBy await User.populate(documentView.fileInfo, { path: 'createdBy', model: 'User', select: 'name isSupportUser isActivated isSubscribed activateBttnClickCount primarySupport' }); console.log(documentView, 'documentView'); return next(null, documentView); }) .catch(err => next(err));
关键注意事项
- 确保Attachment模型中
createdBy字段正确配置了关联:// Attachment Schema需补充ref配置 const AttachmentSchema = new Schema({ // ...其他字段 createdBy: { type: Schema.Types.ObjectId, ref: 'User' }, modifiedBy: { type: Schema.Types.ObjectId, ref: 'User' } }); - 方法一的嵌套填充是Mongoose推荐的多层关联查询方式,代码更简洁且性能更优,避免额外的数据库请求。
内容的提问来源于stack exchange,提问作者Rohit tdr
相关产品推荐
相关产品推荐

