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

MERN Stack实现搜索框正则过滤及发布状态复选框筛选

MERN Stack 多条件搜索与筛选问题解决方案

背景

我正在通过实践学习MERN Stack的协同工作方式,目前跟随bezcoder的Node.js/Express/MongoDb和Reactjs教程学习。

服务器示例数据

[
  {
    "id": "5f9bdace778082303c859248",
    "title": "How to cook noodles",
    "description": "This is a tutorial about how to cook noodles in under 10 minutes.",
    "published": false
  },
  {
    "id": "5f9bdae3778082303c859249",
    "title": "How to bake a chocolate cake",
    "description": "This is a tutorial about how to bake chocolate cake using cocoa powder.",
    "published": true
  }
]

当前状态

目前应用前端有一个搜索框,仅能通过教程的title进行搜索过滤(例如输入"noodles"获取第一条数据),实现代码如下:

1. tutorial.controller.js(后端)

exports.findAll = (req, res) => {
  const title = req.query.title;
  var condition = title ? { title: { $regex: new RegExp(title), $options: "i" } } : {};

  Tutorial.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving tutorials."
      });
    });
};

2. services/tutorial.service.js(React前端)

import http from "../http-common";

class TutorialDataService {

...
  
  findByTitle(title) {
    return http.get(`/tutorials?title=${title}`);
  }
}

export default new TutorialDataService();

需求

希望修改代码,实现通过搜索框同时匹配title和description中的关键词,并通过复选框筛选published:true的数据。

我的尝试

1. tutorial.controller.js(后端,未完成)

exports.findAll = (req, res) => {
  const title = req.query.title || "";
  const description = req.query.description || "";
  const published = req.query.published;

  Tutorial.find(
    {
    $or: [
        {title: { $regex: new RegExp(title), $options: "i"}}, {description: { $regex: new RegExp(description), $options: "i"}}
    ],
    $and: [
        .... and here if checked, then only show published, else show all ....
    ]

}

  )
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving tutorials."
      });
    });
};

2. services/tutorial.service.js(React前端,存疑)

import http from "../http-common";

class TutorialDataService {

...
  
  findByTitle(title, description, published) {
    return http.get(`/tutorials?title=${title}`, `/tutorials?description=${description}`, `/tutorials?published=${published}`);
  }
}

export default new TutorialDataService();

不确定findByTitle的用法是否正确,也不清楚如何正确实现OR和AND查询逻辑。


解决方案

1. 后端(tutorial.controller.js)修改

动态构建MongoDB查询条件,组合模糊搜索与状态筛选逻辑:

exports.findAll = (req, res) => {
  // 获取请求参数:search为搜索框关键词,published为复选框状态
  const search = req.query.search || "";
  const isPublished = req.query.published === "true";

  let query = {};

  // 搜索关键词同时匹配title和description
  if (search) {
    query.$or = [
      { title: { $regex: new RegExp(search), $options: "i" } },
      { description: { $regex: new RegExp(search), $options: "i" } }
    ];
  }

  // 复选框勾选时,添加已发布筛选条件
  if (isPublished) {
    query = query.$or 
      ? { $and: [query.$or, { published: true }] }
      : { published: true };
  }

  Tutorial.find(query)
    .then(data => res.send(data))
    .catch(err => {
      res.status(500).send({
        message: err.message || "获取教程时发生错误。"
      });
    });
};

2. 前端(services/tutorial.service.js)修改

调整请求参数拼接方式,所有查询参数放在同一个URL中:

import http from "../http-common";

class TutorialDataService {

...
  
  searchTutorials(searchTerm, isPublished) {
    const params = new URLSearchParams();
    if (searchTerm) params.append("search", searchTerm);
    if (isPublished) params.append("published", isPublished);

    return http.get(`/tutorials?${params}`);
  }
}

export default new TutorialDataService();

3. 前端组件调用示例

在React搜索组件中,可以这样调用服务方法:

import TutorialDataService from "../services/TutorialDataService";

// 假设searchTerm是搜索框输入值,isPublished是复选框状态
const handleSearch = () => {
  TutorialDataService.searchTutorials(searchTerm, isPublished)
    .then(response => {
      // 更新页面展示的教程数据
      setTutorials(response.data);
    })
    .catch(e => console.error(e));
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:47:03