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

前端 未结 2 984
粉色の甜心
粉色の甜心 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 } });
    

提交回复
热议问题