考虑在使用NodeJS时,在MongoDB Compass中搜索特殊字符的值。

huangapple go评论90阅读模式
英文:

Consider special characters in search of value in MongoDB Compass using NodeJS

问题

我有一条记录,其中包含以下一些值:

[{name: "fdyc+23", size: "s", cost: "250},{name: "1++LION", size: "NA", cost: "180"},{name: "fd_smst", size: "s", cost: "230"},{name: "1-NAKH---", size: "s", cost: "250"},{name: "round .1 mg", size: "s", cost: "250"}]

我想在所有字段上进行搜索。我已经尝试了以下代码片段:

var result = await db.collection.find({
    $or: [{ name: { $regex: <searchInput>, $options: "i" } },
    { size: { $regex: <searchInput>, $options: "i" } },
    { cost: { $regex: <searchInput>, $options: "i" } }]
});

我希望它能处理所有特殊字符或请求参数中提供的任何输入值。

提前感谢。

英文:

I have a record with some values as below:

[{name: "fdyc+23",size: "s",cost: "250},{name: "1++LION",size: "NA", cost: "180"},{name: "fd_smst", size: "s",cost: "230"},{name: "1-NAKH---",size: "s",cost: "250"},{name: "round .1 mg",size: "s",cost: "250"}]

I want to make search on all the fields. I have tried below code snnipet:

    var result = await db.collection.find({
        $or: [{ name: { $regex: &lt;searchInput&gt;, $options: &quot;i&quot; } },
        { size: { $regex: &lt;searchInput&gt;, $options: &quot;i&quot; } },
        { cost: { $regex: &lt;searchInput&gt;, $options: &quot;i&quot; } }]
    });

I want to make it work for all special characters or any sort of input value provided in the request params.

Thanks in advance.

答案1

得分: 1

如果我是你,我会使用自己定义的正则表达式来转义任何特殊字符,我修改了你的代码如下,让我们看看是否在你的端上能够正常工作。

const escapeRegExp = (input) => {
  return input.replace(/[.*+?^${}()|[\]\\]/g, '\$&');
};

const searchInput = req.query.searchInput;
const escapedSearchInput = escapeRegExp(searchInput);

var result = await db.collection.find({
  $or: [
    { name: { $regex: escapedSearchInput, $options: "i" } },
    { size: { $regex: escapedSearchInput, $options: "i" } },
    { cost: { $regex: escapedSearchInput, $options: "i" } }
  ]
});
英文:

If I was you I would use my own defiend regular expression to escape any special characters, I modified your code as below, let's see if it works on your end.

const escapeRegExp = (input) =&gt; {
  return input.replace(/[.*+?^${}()|[\]\\]/g, &#39;\$&amp;&#39;);
};

const searchInput = req.query.searchInput;
const escapedSearchInput = escapeRegExp(searchInput);

var result = await db.collection.find({
  $or: [
    { name: { $regex: escapedSearchInput, $options: &quot;i&quot; } },
    { size: { $regex: escapedSearchInput, $options: &quot;i&quot; } },
    { cost: { $regex: escapedSearchInput, $options: &quot;i&quot; } }
  ]
});

huangapple
  • 本文由 发表于 2023年8月4日 22:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836655.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定