Mongoose: deep population (populate a populated field)

前端 未结 10 600
独厮守ぢ
独厮守ぢ 2020-12-02 08:05

I have Category model:

Category:
    ...
    articles: [{type:ObjectId, ref:\'Article\'}]

Article model contains ref to

10条回答
  •  忘掉有多难
    2020-12-02 08:52

    globals.models.Category.find()
      .where('issue', req.params.id)
      .sort('order')
      .populate('articles')
      .exec(function(err, categories) {
    
        globals.models.Account.populate(categories, 'articles.account', function(err, deepResults){
    
          // deepResult is populated with all three relations
          console.log(deepResults[0].articles[0].account);
    
        });
    });
    

    The following example is inspired by the question asked @codephobia and populates two levels of many relationships. First fetch a user, populate its array of related orders and include each orderDetail.

    user.model.findOne()
      .where('email', '***@****.com')
      .populate('orders')
      .exec(function(err, user) {
    
        orderDetail.model.populate(user, 'orders.orderDetails', function(err, results){
    
          // results -> user.orders[].orderDetails[] 
        });
    });
    

    This works fine in 3.8.8 but should work in 3.6.x.

提交回复
热议问题