My user schema is structured as shown below
const userSchema = mongoose.Schema({
username: {
type: String,
required: true,
},
first_name: {
type: String,
required: true,
},
last_name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
otp: {
type: String,
},
phone_number: {
type: String,
required: true,
},
resetPasswordToken: {
type: String,
},
resetPasswordExpires: {
type: Date,
}
}, { timestamps: true });
role schema
import mongoose from 'mongoose';
const roleSchema = mongoose.Schema({
name: {
type: String,
required: true
},
}, { timestamps: true })
export default mongoose.model('Role', roleSchema);
and user role schema:
import mongoose from 'mongoose';
const userRoleSchema = mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User",
unique: true,
},
roleId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "Role",
unique: true,
}
}, { timestamps: true })
export default mongoose.model('UserRole', userRoleSchema);
I am looking for a more efficient way to retrieve the user object along with their corresponding role in Mongoose. Instead of relying on pivots, is there a simpler approach I can take? This is important because my design involves multiple objects connected through pivot tables.
User->userRole->Role Additionally;
User->userPermission->Permission
I understand that I could use the populate method for relationships, but only if I have the roles and permissions fields directly within the user schema referencing the role and permission schemas.
In essence, I need a cleaner way to link these schema objects without having to manually fetch the associated role information as illustrated below. My goal is to obtain a complete user object with the role name and also include permissions.
let user = User.getRole(1); // find user
let userRole = UserRole.where('userId',1); // determine the user role
let role = Role.findOne(userRole.roleId); // get the specific role
user.role = role.name; // add role name to user object
The same concept applies to rolePermission pivots for associating roles with permissions and direct userPermission pivots.