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

前端 未结 2 966
粉色の甜心
粉色の甜心 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:14

    If you want to get a ProjectGroup object, which contains all the projects under that group. You can use Populate Virtuals. (Mongoose version > 4.5.0)

    create a virtual schema in your schema file.

    ProjectGroupSchema.virtual('projects', {
      ref: 'Project', // The model to use
      localField: 'projectGroupId', // Your local field, like a `FOREIGN KEY` in RDS
      foreignField: 'group', // Your foreign field which `localField` linked to. Like `REFERENCES` in RDS
      // If `justOne` is true, 'members' will be a single doc as opposed to
      // an array. `justOne` is false by default.
      justOne: false
    });
    

    and query in following:

    ProjectGroup.find().populate('projects').exec(function(error, results) {
      /* `results.projects` is now an array of instances of `Project` */
    });
    

    If you cannot see virtuals part, plese set { toJSON: { virtuals: true } } to your model.

    var ProjectGroupSchema = new Schema({
        projectGroupId    : String,
        title             : String
    }, { toJSON: { virtuals: true } });
    
    0 讨论(0)
  • 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);
        });
    
    });
    
    0 讨论(0)
提交回复
热议问题