Mongoose: deep population (populate a populated field)

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

    Easiest way to accomplish this in 3.6 is to use Model.populate.

    User.findById(user.id).select('-salt -hashedPassword').populate('favorites.things').exec(function(err, user){
        if ( err ) return res.json(400, err);
    
        Thing.populate(user.favorites.things, {
            path: 'creator'
            , select: '-salt -hashedPassword'
        }, function(err, things){
            if ( err ) return res.json(400, err);
    
            user.favorites.things = things;
    
            res.send(user.favorites);
        });
    });
    

提交回复
热议问题