【问题标题】:search doesn't get result when the search term contains () after a word当搜索词在单词后包含 () 时,搜索不会得到结果
【发布时间】:2021-08-06 10:35:27
【问题描述】:

例如,如果有名称为“playstation (white)”的产品,如果我搜索“playstation”或“white”甚至是“(白色)”,结果显示。但如果我搜索“playstation(白色)”,结果为空。

我认为这个错误是由于正则表达式,因为当我尝试输入例如:'playstation ('

出现此错误Regular expression is invalid: missing)。但我不知道如何解决。

当我尝试搜索“playstation /(white/)”时,

假设有 3 种产品:playstation(白色)playstation(黑色)xbox

它显示playstation(白色)playstation(黑色)

这是我的代码

后端productController.js

const getProducts = asyncHandler(async (req, res) => {
  const pageSize = 10
  const page = Number(req.query.pageNumber) || 1

  const keyword = req.query.keyword
    ? {
        name: {
          $regex: req.query.keyword,
          $options: 'i',
        },
      }
    : {}

  const count = await Product.countDocuments({ ...keyword })
  const products = await Product.find({ ...keyword })
    .limit(pageSize)
    .skip(pageSize * (page - 1))

  res.json({ products, page, pages: Math.ceil(count / pageSize) })
})

前端 searchBox.js

import React, { useState } from "react";
import { Form } from "react-bootstrap";

const SearchBox = ({ history }) => {
  const [keyword, setKeyword] = useState("");

  const submitHandler = (e) => {
    e.preventDefault();
    if (keyword.trim()) {
      history.push(`/search/${keyword}`);
    } else {
      history.push("/");
    }
  };

  return (
    <Form onSubmit={submitHandler}>
      <Form.Control
        type="text"
        name="q"
        onChange={(e) => setKeyword(e.target.value)}
        placeholder="Search...."
        className="search-box"
        /* className="mr-sm-2 ml-sm-5" */
      ></Form.Control>
      {/*  <Button type="submit" variant="outline-success" className="p-2">
        <div style={{ color: "white" }}>Search</div>
      </Button> */}
    </Form>
  );
};

export default SearchBox;

【问题讨论】:

    标签: javascript node.js reactjs regex


    【解决方案1】:

    首先,如果您想使用$regex,您需要对从用户那里获得的字符串中的特殊符号进行转义。

    但是有一个更好的解决方案,我建议你使用 MongoDD 的文本搜索功能。你可以在这里阅读它https://docs.mongodb.com/manual/text-search/https://docs.mongodb.com/manual/text-search/这个填充让你可以使用全文搜索。

    简而言之,您需要执行以下操作:

    1. 为要在搜索中使用的字段创建索引。
    2. 将查询更改为使用$text$search 运算符。

    【讨论】: