如何在AdminJS中基于用户属性实现任务集合的嵌套过滤
问题
使用AdminJS管理Users和Tasks两个集合,其中Users包含Unit、fullName、email、phone_number等属性。当前Tasks页面仅支持通过用户邮箱过滤任务,需要配置实现基于用户的Unit、fullName等属性过滤任务。
解决方案
要实现关联用户属性的过滤,需在Tasks资源配置中手动定义关联字段的过滤规则,具体操作如下:
- 扩展过滤属性列表:在Tasks的
filterProperties中添加用户关联的嵌套字段,比如user.fullName、user.Unit。 - 显式定义字段配置:通过
properties选项指定这些嵌套字段的类型和展示标签,确保AdminJS能正确识别并渲染过滤组件。 - 确认关联关系有效性:确保Tasks集合中的
user字段是与Users集合的合法关联引用(如MongoDB的ObjectId关联),保证关联查询能正常执行。
修改后的完整代码
const contentParent = { name: "Employees", icon: "User", }; const adminOptions = { resources: [ { resource: tasks, options: { listProperties: ["user", "date", "submitted"], // 扩展过滤属性,加入用户的嵌套字段 filterProperties: ["user", "user.fullName", "user.Unit", "date", "submitted"], actions: { new: { isAccessible: false }, delete: { isAccessible: false }, }, parent: contentParent, sort: { sortBy: "date", direction: "desc", }, // 定义嵌套字段的类型与展示标签 properties: { "user.fullName": { type: "string", label: "用户全名", }, "user.Unit": { type: "string", label: "用户部门", }, }, }, }, { resource: Users, options: { actions: { new: { isAccessible: true, History: false, before: async (request) => { if (request.payload.password) { const salt = await bcrypt.genSalt(12); const hashedPassword = await bcrypt.hash( request.payload.password, salt ); request.payload = { ...request.payload, password: hashedPassword, created_at: new Date(), }; } return request; }, }, delete: { isAccessible: false }, }, parent: contentParent, sort: { sortBy: "created_at", direction: "desc", }, }, }, ], componentLoader, }; const admin = new AdminJS({ ...adminOptions, defaultTheme: light.id, availableThemes: [dark, light, noSidebar], branding: { companyName: "Tasks", withMadeWithLove: false, }, }); const adminRouter = AdminJSExpress.buildRouter(admin); app.use(admin.options.rootPath, adminRouter);
额外说明
- 若使用MongoDB,需保证Tasks集合的
user字段是指向Users集合的ObjectId类型,AdminJS会自动处理跨集合的关联过滤查询。 - 如果需要更复杂的过滤逻辑(如模糊匹配),可以通过自定义
filters函数实现,针对特定字段编写过滤规则。
内容的提问来源于stack exchange,提问作者Rawand ofj
相关产品推荐
相关产品推荐

