嵌套数组上的猫鼬“填充”返回null

时间:2020-06-20 21:25:22

标签: node.js mongodb mongoose

我最近开始对我的一个API请求使用猫鼬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);

以上填充在该场所运行正常(可能是因为我仅填充了一个深处)。但是我似乎无法找到适合该食物的填充物,它总是返回null。

我尝试过:

.populate('foods.food')

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

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

我该如何实现?谢谢。

0 个答案:

没有答案