in my case, I've 3 tables
users table
name: {
type: String,
required: [true, 'Email is required'],
trim: true,
lowercase: true,
},
role: {
type: String,
required: true,
enum: ['SUPER_ADMIN', 'ROOT_STANDERD', 'COMPANY_ADMIN', 'RETAILER_ADMIN']
},
company: {
type: ObjectId,
ref: 'company',
},
retailer: {
type: ObjectId,
ref: 'retailer'
}
});
Company Table
const CompanySchema = new Schema({
_id: String,
name: {
type: String,
required: true,
maxLength: 50,
}})
Retailer Table
const CompanySchema = new Schema({
_id: String,
name: {
type: String,
required: true,
maxLength: 50,
},
company: {
type: ObjectId,
ref: 'company',
}})
Let me explain how it works:
SUPER_ADMIN
can create the company, retailer(it will reference by Company), and user (if the user role is COMPANY_ADMIN
then the user is referenced by company, and if the user role is RETAILER_ADMIN
then the user is the reference by retailer)
SUPER_ADMIN
can view all the users
Now my query is COMPANY_ADMIN
can view their related company's user and retailer's user only.
In this case you can try customize query, you can try this
user.find({ $or: [{ retailer: { $in: [retailer_id1, retailer_id2...] } }, { company: user.company }] })