如何重构$expr、$regexMatch过滤器以提升React/MongoDB代码可读性
代码优化方案
核心优化点
- 简化查询key逻辑:空数组展开无额外元素,直接展开
currentOperatorsIds即可,删除多余长度判断 - 抽离重复的正则配置:姓名匹配的正则参数除了拼接格式完全一致,复用配置减少重复代码
- 合并entities查询条件:避免重复写两遍相同的entities判断逻辑,通过动态注入姓名匹配表达式精简代码
- 移除冗余的临时变量:查询函数直接返回接口调用结果即可,无需额外赋值
- 修复原代码隐式问题:补充查询函数的return语句(原代码未返回查询结果会导致useQuery拿不到data)
优化后完整代码
const { data: packUsersData } = useQuery( ["pack", id, "users", ...currentOperatorsIds, value], async () => { // 抽离公共正则配置 const regexConfig = { regex: value, options: "i" }; // 姓名匹配表达式,无搜索值时返回空对象 const nameMatch = value ? { $expr: { $or: [ { $regexMatch: { input: { $concat: ["$firstName", " ", "$lastName"] }, ...regexConfig } }, { $regexMatch: { input: { $concat: ["$lastName", " ", "$firstName"] }, ...regexConfig } } ] } } : {}; return usersApi.getrs({ pagination: false, query: { "roles.name": "operator", _id: { $nin: currentOperatorsIds }, deletedAt: null, $or: [ { entities: [], ...nameMatch }, { entities: { $in: id }, ...nameMatch } ] }, populate: "entity", sort: ["lastName", "firstName"] }); }, { refetchOnMount: true } );
如果使用MongoDB 3.6以上版本,还可以进一步合并entities的判断条件,直接删除$or字段,代码更精简:
query: { "roles.name": "operator", _id: { $nin: currentOperatorsIds }, deletedAt: null, entities: { $in: [[], id] }, ...nameMatch }
内容的提问来源于stack exchange,提问作者Neff
相关产品推荐
相关产品推荐

