So I have a schema with people and groups. I want to make it possible for a person to be related to one or more people or groups. So far I have this:
var PersonSchema = new Schema({
name : String,
});
var PersonModel = mongoose.model('Person', PersonSchema);
var GroupSchema = new Schema({
name : String,
members : [PersonSchema]
});
var GroupModel = mongoose.model('Group', GroupSchema);
How to add to PersonSchema a set of one or more groups and/or other people?
Assuming you have both Persons
and Groups
collections in your database based on this, you could add arrays of ObjectId refs to PersonSchema to capture a person's relationships with other people or groups. As in:
var PersonSchema = new Schema({
name : String,
people: [{ type: Schema.ObjectId, ref: 'Person' }],
groups: [{ type: Schema.ObjectId, ref: 'Group' }]
});
Then you can use mongoose's populate
support to follow those refs whenever you need their full details.
You can define like:
var Relation = new mongoose.Schema({
RelationType:String, RefObjId: String //You can also take Schema.ObjectId
});
var PersonObj = new mongoose.Schema({
name: String,
OtherDetails: String,
RefObjDetails:[Relation]
});
Example:
A (_id:100) Person is related to B (_id:200) Person and to group MyGroup (_id:333).
JSON will look like:
{
'_id':'100',
'name': 'A',
'OtherDetails': '',
'RefObjDetails':[{'RelationType':'P', RefObjId:'200'},{'RelationType':'G', RefObjId:'333'}]
}