MongoDB与NextJS实现新冠疫情数据不区分大小写国家搜索功能
实现MongoDB+NextJS下不区分大小写国家名称搜索的方案
你可以根据自己的业务场景选择以下两种实现方式:
方案1:MongoDB端查询实现(更推荐,适合数据量较大、搜索频率高的场景)
直接在NextJS的API路由中构造忽略大小写的MongoDB查询规则,无需改动前端现有逻辑,查询效率更高:
快速实现(正则匹配)
用$regex搭配i参数实现忽略大小写的完全匹配:// NextJS API路由内的MongoDB查询代码 const country = await db.collection('countries').findOne({ country_name: { $regex: new RegExp(`^${targetCountry}$`), $options: 'i' } })其中
^和$用来限定完全匹配国家名称,若需要实现前缀模糊搜索可以去掉这两个符号。高性能实现(加索引优化)
如果国家名称搜索是高频操作,可以先给country_name字段建立忽略大小写的索引,查询性能比正则方式高30%以上:
第一步先执行一次建索引操作(可在Mongo Shell或者项目初始化脚本中运行):db.countries.createIndex({ country_name: 1 }, { collation: { locale: 'en', strength: 2 } })第二步查询时指定相同的排序规则即可:
const country = await db.collection('countries').findOne( { country_name: targetCountry }, { collation: { locale: 'en', strength: 2 } } )这里的
strength: 2就是MongoDB定义的忽略大小写的匹配规则。
方案2:前端兼容实现(适合已经全量拉取国家数据到前端、不想改动后端逻辑的场景)
直接修改现有搜索函数,将国家名称和搜索关键词统一转为小写/大写后再比较即可,同时还可以简化冗余的判断逻辑:
const search = (e) => { e.preventDefault() //避免页面重定向 // 统一转小写后匹配,自动忽略大小写差异 const countryMatch = countryCollection.find(country => country.country_name.toLowerCase() === targetCountry.toLowerCase() ) if (!countryMatch) { alert("国家不存在,请换个名称重试。") setName("") setTargetCountry("") } else { setName(countryMatch.country_name) setDeathCount(toNum(countryMatch.deaths)) setCriticalCount(toNum(countryMatch.serious_critical)) setRecoveryCount(toNum(countryMatch.total_recovered)) } }
原有代码中!countryMatch已经覆盖了值为null、undefined的情况,不需要重复判断。
内容的提问来源于stack exchange,提问作者Mark Willow Aldave
相关产品推荐
相关产品推荐

