Let\'s borrow the excellent example from scaryguy with modification as below:
Project Group Schema:
var ProjectGroupSchema = new Schema({
project
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 } });