I am trying to build an app that has enterprises, enterprise users and users. I have come up with these schemas/models.
var enterpriseSchema = new Schema({
enterpriseId : ObjectId,
enterpriseName : {type: String, index: true},
enterpriseUsers : [enterpriseUserSchema],
owner : {type: ObjectId, ref: 'User'}
});
var enterpriseUserSchema = new Schema({
user : {type: ObjectId, ref: 'User'},
role : {type: String, index: true},
lastAccess : Date
});
var userSchema = new Schema({
userId : ObjectId,
givenName : String,
middleName : String,
familyName : String,
username : { type: String, unique: true, index: true },
password : String,
enterprise : {type: ObjectId, ref: 'Enterprise'}
});
var User = mongoose.model('User', userSchema);
var Enterprise = mongoose.model('Enterprise', enterpriseSchema);
Note the enterpriseUsersSchema. This seems like a reasonable way to reference enterprise users. Is it, or is there a better way?
If I use these schemas/models, how would I go about populating the users of an enterprise? I would need givenName, familyName and role for each user. I have tried populate but I can't determine how to populate users given the enterpriseUsersSchema.