JavaScript:未指定title参数时过滤查询无法返回所有Cards如何修正
问题分析
- 原代码的where条件中title的筛选逻辑存在错误:你试图添加的
|| ""并没有生效,因为模板字符串%${title}%会优先执行拼接,当接口没有传入title参数时,title的值为undefined,拼接后会得到%undefined%,此时会去匹配title字段中包含undefined字符串的记录,自然无法返回正确结果。 - 原写法不管是否传入title都会强制添加title的匹配条件,不符合“没有title就返回所有匹配authorid的记录”的需求。
修改方案
你需要动态构建where查询条件,仅当title存在有效值时才添加title的模糊匹配规则,修改后的代码如下:
//Finds All of the User's Cards, and allows Searching by Title exports.findMyCards2 = (req, res) => { const { page, size, title, authorid } = req.query; const { limit, offset } = getPagination(page, size); // 动态构建where条件 const whereCondition = { authorid: { [Op.like]: `%${authorid}%` } }; // 只有title存在非空值时才添加title筛选 if (title && title.trim()) { whereCondition.title = { [Op.like]: `%${title}%` }; } Card.findAndCountAll({ limit, offset, where: whereCondition }) .then(data => { const response = getPagingData(data, page, limit); res.send(response); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving Cards." }); }); };
补充说明
- 如果你的业务逻辑允许传入空字符串作为title的匹配条件,可根据实际需求调整
if (title && title.trim())的判断规则。 - 原来的
|| ""写法位置错误,逻辑运算符的优先级低于模板字符串拼接,所以不会起到你预期的默认值效果。
内容的提问来源于stack exchange,提问作者SomethingTester123
相关产品推荐
相关产品推荐

