Mongoose: deep population (populate a populated field)

前端 未结 10 539
独厮守ぢ
独厮守ぢ 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:58

    If you want select multi populate inside populate, you should try this way:

    I have Booking schema:

    let Booking = new Schema({
      ...,  // others field of collection
      experience: { type: Schema.Types.ObjectId, ref: 'Experience' },
      ...},{
        collection: 'booking'
      });
    

    and Experience schema:

    let Experience = new Schema({
      ...,
      experienceType: {type: Schema.Types.ObjectId, ref: 'ExperienceType'},
      location: {type: Schema.Types.ObjectId, ref: 'Location'},
      ...} // others field of collection
      ,{
        collection: 'experience'
      });
    

    get ExperienceType and Location of Experience when you find Booking:

    Booking.findOne({_id: req.params.id})
      .populate({path: 'experience',
        populate: [{path: 'experienceType', select: 'name'}, {path: 'location', select: 'name'}],
      })
      .exec((err, booking) => {
        if(err){
          console.log(err);
        }
        else {
          res.json(booking);
        }
      });
    
    0 讨论(0)
  • 2020-12-02 08:59

    Firstly, update mongoose 3 to 4 & then use the simplest way for deep population in mongoose as below :

    Suppose you have Blog schema having userId as ref Id & then in User you have some review as ref Id for schema Review. So Basically, you have three schema : 1. Blog 2. User 3. Review

    And, you have to query from blog, which user owns this blog & the user review. So you can query your result as :

    BlogModel
      .find({})
      .populate({
        path : 'userId',
        populate : {
          path : 'reviewId'
        }
      })
      .exec(function (err, res) {
    
      })
    
    0 讨论(0)
  • 2020-12-02 09:02

    Sorry to burst your bubble, but there's not a directly supported solution to this. As for Github issue #601, it looks grim. According to the 3.6 release notes, it looks like the developers acknowledged the issue are happy with manual recursive/deep population.

    So from the release notes, the recommended method is to nest populated calls in the callback, so in your exec() function, use categories.populate to further populate before sending a response.

    0 讨论(0)
  • Or you can pass Object to the populate method as:

    const myFilterObj = {};
    const populateObj = {
                    path: "parentFileds",
                    populate: {
                        path: "childFileds",
                        select: "childFiledsToSelect"
                    },
                    select: "parentFiledsToSelect"
                   };
    Model.find(myFilterObj)
         .populate(populateObj).exec((err, data) => console.log(data) );
    
    0 讨论(0)
提交回复
热议问题