英文:
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: <searchInput>, $options: "i" } },
{ size: { $regex: <searchInput>, $options: "i" } },
{ cost: { $regex: <searchInput>, $options: "i" } }]
});
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) => {
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" } }
]
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论