Mongoose: deep population (populate a populated field)

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

    Populating across multiple levels

    Say you have a user schema which keeps track of the user's friends.

    var userSchema = new Schema({
      name: String,
      friends: [{ type: ObjectId, ref: 'User' }]
    });
    

    Populate lets you get a list of a user's friends, but what if you also wanted a user's friends of friends? Specify the populate option to tell mongoose to populate the friends array of all the user's friends:

    User.findOne({ name: 'Val' }).populate({
        path: 'friends',
        // Get friends of friends - populate the 'friends' array for every friend
        populate: { path: 'friends' }
    });
    

    Reference: http://mongoosejs.com/docs/populate.html#deep-populate

提交回复
热议问题