首页 > 解决方案 > 嵌套数组上的猫鼬“填充”返回 null

问题描述

我最近开始populate对我的一个 API 请求使用 mongoose 选项,该选项适用于标准对象和模式,但我正在努力使其适用于嵌套数组。

我的架构如下所示(这是我尝试使用populate检索的架构):

const FoodSchema = new Schema( {
   name: {type: String, required: true},
   price: {type: String, required: true},
   category: {type: String, required: true},
   ... 
})

然后我有:

const OrderFoodSchema = new Schema(
{
  food: {type: Schema.Types.ObjectId, required: true, ref: 'food'},
  quantity: {...},
  price: {...},
},
{ _id: false });

&&

const OrderSchema = new Schema( {
  customer: {...},
  venue: {type: Schema.Types.ObjectId, required: true, ref: 'venue'},
  foods: [OrderFoodSchema]
})

我获取数据的查询是:

return Order.findOne({ _id: order_id, customer: user._id })
   .populate({path:'venue',select:['name','address','contact']})
   .orFail()
   .then(function(order) {
     res.json(order)
   }) 
   .catch(next);

上面的填充适用于场地(可能是因为我只填充了一层)。但我似乎无法为食物找到一个有效的人口,它总是返回空值。

我努力了:

.populate('foods.food')

.populate({path:'foods.food'})

.populate({ 
 path: 'foods',
 populate: {
   path: 'food',
   } 
 })

我怎样才能做到这一点?谢谢。

标签: node.jsmongodbmongoose

解决方案


推荐阅读