MongoDB在$or中使用$regex报错'regex has to be a string'如何解决
错误根因
你遇到的$regex has to be a string报错,核心原因是$regex运算符必须接收字符串类型的参数,当你的GET请求没有同时传递keyword和category两个查询参数时,queryStr.keyword或queryStr.category会是undefined,不符合$regex的参数要求。单独用$regex没报错是因为你当时传了对应参数,值为有效字符串。
解决方案
你需要动态构建查询条件数组,只有对应查询参数存在且为非空字符串时,才把该字段的匹配规则加入$or数组,修改后的代码如下:
app.route("/product") .get(function(req, res){ const queryStr = req.query; // 初始化$or条件数组 const orConditions = []; // 仅当keyword参数存在且为字符串时,加入name匹配规则 if (queryStr.keyword && typeof queryStr.keyword === 'string') { orConditions.push({ name:{ $regex: queryStr.keyword, $options: 'i'}}); } // 仅当category参数存在且为字符串时,加入category匹配规则 if (queryStr.category && typeof queryStr.category === 'string') { orConditions.push({category: {$regex: queryStr.category, $options: 'i'} }); } // 处理无有效查询参数的场景,避免$or为空数组报错 const query = orConditions.length > 0 ? { $or: orConditions } : {}; Product.find(query, function(err, docs){ if(!err){ res.send({ success: true, count: docs.length, docs }) } else { res.send(err.stack) } }) })
额外优化说明
- 如果业务要求请求必须至少传递两个参数中的一个,可以在构建查询前增加参数校验,参数不全直接返回400错误,减少无效数据库查询
- 可自行对传入的keyword、category做正则特殊字符转义处理,避免特殊字符导致的查询逻辑异常
内容的提问来源于stack exchange,提问作者vinuka pussepitiya
相关产品推荐
相关产品推荐

