如何在Mongoose中为中间件返回的对象执行populate关联查询
错误原因
你拿到的storeObj是普通JS对象(非Mongoose Document实例),只有Mongoose查询返回的文档实例才自带populate实例方法,因此调用时报方法不存在的错误。
解决方案
方案1:上游查询时直接填充(推荐)
可以在第一个中间件查询ExtractedSchema时就完成嵌套字段的关联填充,后续中间件直接使用填充后的数据即可,示例代码:
// 第一个中间件的查询逻辑 const result = await extractedSchema.findOne(你的查询条件) // 按嵌套路径逐层指定要填充的字段 .populate('storeObjParent.storeObj.StoreId') .populate('storeObjParent.storeObj.Products.PrdId'); // 挂载到req上的storeObj就已经是填充后的结构 req.storeObj = result.storeObjParent.storeObj;
方案2:对现有普通对象执行静态填充
如果无法修改上游中间件的查询逻辑,可以使用Mongoose内置的静态populate方法直接对普通对象执行填充,无需依赖文档实例:
const mongoose = require('mongoose'); // storeObj是你从req上拿到的数组结构,直接传入即可 const storeObjWithDetails = await mongoose.populate(storeObj, [ { path: 'StoreId', model: 'Store' }, { path: 'Products.PrdId', model: 'Product' } ]); // 你场景下只有一条门店数据,直接取第一个元素即可 const finalStoreData = storeObjWithDetails[0];
注:Mongoose 6+ 版本已经废弃
execPopulate()方法,populate调用后直接await即可拿到结果。
内容的提问来源于stack exchange,提问作者Nishant S Vispute
相关产品推荐
相关产品推荐

