You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB按名称搜索用户却返回全部用户的问题排查

问题:通过name字段模糊查询用户却返回全部数据

问题背景

尝试通过name字段查询用户,在Insomnia中测试时,本该返回name包含指定关键词的用户,但却返回了数据库中全部用户。相关代码如下:

用户Schema

const userSchema = mongoose.Schema({
  id: { type: String },
  name: {
    type: String,
    required: true,
  },
  companion: {
    type: String,
    required: false
  },
  bio: { 
    type: String,
    required: false
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
    min: 5
  },
  userImage: {
    type: String,
    required: false,
  },
});

路由配置

router.get('/search', getUserBySearch)

查询函数逻辑

export const getUserBySearch = async (req, res) => {
                         // tried req.query and req.query.search
  const { searchQuery } = req.params
  try {
              // make the search query not case sensitive
    const user = new RegExp(searchQuery, `i`)

    //find the user's name using the name field
    const userFound = await User.find({name: user})
    res.json({data: userFound})

  } catch (error) {
    res.status(404).json({message: error.message})
  }
}

测试URL

http://localhost:3001/user/search?searchQuery=test

问题原因与修正方案

核心错误

  1. 参数获取方式错误:URL中的?searchQuery=test属于查询参数,需要通过req.query获取,而非req.params(req.params用于匹配路由中的占位符,比如/search/:searchQuery)。
  2. 空值未处理:当searchQuery未正确获取时,值为undefined,此时new RegExp(undefined, 'i')会生成/(?:)/i——这个正则会匹配所有字符串,导致MongoDB返回全部用户。

修正后的代码

export const getUserBySearch = async (req, res) => {
  const { searchQuery } = req.query;
  try {
    // 处理查询参数为空的情况,避免匹配全部用户
    if (!searchQuery) {
      return res.json({ data: [] });
    }
    // 构造不区分大小写的正则表达式
    const nameRegex = new RegExp(searchQuery, 'i');
    // 查询name字段匹配正则的用户
    const userFound = await User.find({ name: nameRegex });
    res.json({ data: userFound });
  } catch (error) {
    res.status(404).json({ message: error.message });
  }
};

额外优化建议

如果需要更贴合MongoDB查询规范的写法,可以使用$regex操作符结合$options实现相同效果:

const userFound = await User.find({ 
  name: { 
    $regex: searchQuery, 
    $options: 'i' 
  } 
});

内容的提问来源于stack exchange,提问作者paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 12:12:24