如何在MongoDB与Node.js中关联3张表并实现COMPANY_ADMIN权限查询
需求实现:COMPANY_ADMIN 用户权限查询控制
场景背景
数据库表结构
1. users 表(Mongoose Schema)
const UserSchema = new Schema({ 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' } });
2. Company 表(Mongoose Schema)
const CompanySchema = new Schema({ _id: String, name: { type: String, required: true, maxLength: 50, } });
3. Retailer 表(Mongoose Schema)
const RetailerSchema = new Schema({ _id: String, name: { type: String, required: true, maxLength: 50, }, company: { type: ObjectId, ref: 'company', } });
现有业务规则
- SUPER_ADMIN:
- 可创建公司、关联公司的零售商,以及各类用户
- 创建用户时,
COMPANY_ADMIN需关联对应公司;RETAILER_ADMIN需关联对应零售商 - 可查看所有用户
核心需求实现
实现 COMPANY_ADMIN 仅能查看两类用户:
- 所属同一公司的所有用户
- 该公司下属所有零售商关联的所有用户
具体实现代码(基于 Mongoose)
// 假设已通过鉴权获取当前登录的 COMPANY_ADMIN 用户:currentUser const currentCompanyId = currentUser.company; // 第一步:获取当前公司下属的所有零售商ID列表 const retailerIds = await Retailer.find({ company: currentCompanyId }).distinct('_id'); // 第二步:查询符合权限的用户 const allowedUsers = await User.find({ $or: [ // 条件1:用户直接关联当前公司 { company: currentCompanyId }, // 条件2:用户关联的零售商属于当前公司 { retailer: { $in: retailerIds } } ] }) // 可选:关联查询公司/零售商名称,返回更完整数据 .populate('company', 'name') .populate('retailer', 'name');
逻辑说明
- 用
$or组合双条件,覆盖所有符合权限的用户范围 - 通过
distinct('_id')高效去重获取零售商ID,避免冗余数据 - 可选的
populate方法可补充关联实体的名称信息,提升接口实用性
内容的提问来源于stack exchange,提问作者Smit lathiya
相关产品推荐
相关产品推荐

