I am developing my first database in Mongo . I m using Mongoose to create the models . I want to implement a multiple relationship one to many. There are three models :User, Group and Role Model. where a user can belong to multiple groups and can have several roles in the same group. For example, John belongs to group 1 and 2. Juan in group 1 is administrator and the group 2 is administrator and superuser. Below I show the relational schema:
I have create the follow models:
UserModel
const userSchema = new Schema({
username: {type: String, unique: true},
first_name: String,
middle_name: String,
first_surname: String,
second_surname: String,
email: String,
password: String
}, {
timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleteAt: 'delete_at'}
});
const UserModel = mongoose.model('user', userSchema);
RoleModel
const roleSchema = new Schema({
name: {type: String, unique: true},
code: {type: String, unique: true},
description: String
}, {
timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleteAt: 'delete_at'}
});
const RoleModel=mongoose.model('role', roleSchema);
GroupModel
const groupSchema = new Schema({
name: {type: String, unique: true}
}, {
timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleteAt: 'delete_at'}
});
const GroupSchema = mongoose.model('group', groupSchema);
GroupUserRoleModel
const groupuserroleSchema = new Schema({
role: {type: Schema.Types.ObjectID, ref: 'role'},
user: {type: Schema.Types.ObjectID, ref: 'user'},
group: {type: Schema.Types.ObjectID, ref: 'group'}
});
const GroupUserRoleModel = mongoose.model('group_user_role', groupuserroleSchema);
My questions are:
- This OK the implementations?
- When I want create an GroupUserRole document , how do it?
I have seen information about the method populate in mongoose (Populate) but only there is one relation ship between two models Thank for your help.