我想在我的服务器端找到一个mongo查询,我的查询就像这样
{
$text: { $search: "beautiful" },
"Category": {
$elemMatch: {
"title": { $in: [/Home/] }
}
},
"Company": { $regex: /philips/i }
}
对于上面的查询,我得到了我想要的确切结果,但我的问题是,公司名称"philips"
是从我的html页面到服务器端,在服务器端它尝试将其转换为{{1为了在查询中使用它,但它在mongo查询中作为字符串。
我尝试了什么:
/philips/i
我的期望:
var productCompany = philips; // <---(getting this from my html page)
var productCmpnyRegex = '/' + productCompany + '/i';
query = {
$text: { $search: "beautiful" },
"Category": {
$elemMatch: {
"title": { $in: [/Home/] }
}
},
"Company": { $regex: productCmpnyRegex }
}
但它正在将其视为
query = {
$text: { $search: "beautiful" },
"Category": {
$elemMatch: {
"title": { $in: [/Home/] }
}
},
"Company": { $regex: /philips/i }
}
答案 0 :(得分:2)
在 RegExp
构造函数中包装正则表达式模式,该构造函数创建一个正则表达式对象,用于将文本与模式匹配:
var productCmpnyRegex = new RegExp(philips, 'i'); // <-- creates a regex obj /philips/i;
query = {
"$text": { "$search": "beautiful" },
"Category": {
"$elemMatch": {
"title": { "$in": [/Home/] }
}
},
"Company": productCmpnyRegex
}