Mongoose 'reversed' population, i.e. populating a parent object based on the reference defined in child schema

前端 未结 2 965
粉色の甜心
粉色の甜心 2020-12-17 22:37

Let\'s borrow the excellent example from scaryguy with modification as below:

Project Group Schema:

var ProjectGroupSchema = new Schema({
    project         


        
2条回答
  •  隐瞒了意图╮
    2020-12-17 23:39

    You can achieve this by using aggregate function. First group projects by "projectGroup" and then populate result.

    project.aggregate([
       {$group: {_id: "$group", projects: {$push: "$$ROOT"}}}
    ],
      function(err,results) {
        user.populate( results, { "path": "projects.subscribers" }, function(err,results) {
            if (err)
             console.log(err);
            res.send(results);
        });
    
    });
    

提交回复
热议问题