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

Mongoose中$or与正则表达式结合搜索失效问题

问题分析与解决方案

你的查询条件字段路径错误,导致MongoDB无法正确匹配目标字段,最终返回了所有文档。

问题根源

从你的Model定义和返回的文档结构可明确:

  • title 是嵌套在顶级字段 toDoTitle 下的子字段
  • tasks 是嵌套在顶级字段 toDoTasks 下的子字段

但你在查询时直接使用了title和tasks作为顶级字段,MongoDB找不到这些字段,因此所有文档都被错误匹配返回。

修复后的控制器代码

修改查询条件中的字段路径,使用正确的嵌套字段路径:

//importing model
const toDoModel = require('../models/ToDoModel');

//importing utils function
const toDosPerPage = require("../utlis/ToDosPerPage")

const searchController = async (req,res)=>{
    try{
        const {filter} = req.query
        if(!filter) throw new Error("Please provide Something in filter to search");
        const filteredArray = await toDoModel.find({
            $or:[
                {"toDoTitle.title": new RegExp(filter,'i')},
                {"toDoTasks.tasks": new RegExp(filter,'i')}
            ]
        });
        
        res.status(200).json({
            success: true,
            message: "Successfully fetched todos",
            filteredArray
        });
    }
    catch(err){
        res.status(401).json({
            success: false,
            message: "Some error occuried",
            error: err.message
        })
        console.log(err.message);
    } 
}
module.exports = searchController;

关键说明

  1. toDoTitle.title:精准指向嵌套在toDoTitle下的title字段,实现模糊搜索
  2. toDoTasks.tasks:指向嵌套在toDoTasks下的数组字段,MongoDB会自动检查数组中是否有元素匹配正则表达式
  3. 正则的'i'标志实现不区分大小写的搜索

修改后,访问localhost:4000/search?filter=Morning时,只会返回toDoTitle.title包含Morning或toDoTasks.tasks数组中包含Morning的文档。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:00:55