mongodb正则表达式在流星中搜索问题

Sas*_*nth 5 regex mongodb meteor

我的代码是

var search_element=Session.get("search_string");
var adc="/"+search_element+"*/";
console.log(adc);
return Polls_Coll.find({question:{$regex:adc}});
Run Code Online (Sandbox Code Playgroud)

为什么它不起作用

如果我给

Polls_Coll.find({question:{$regex:/Best*/}});

在conslow它正在工作,如果我用值(search_element)替换正则表达式它是不工作的.我认为它正在取代这样

Polls_Coll.find({question:{$regex:"/Best*/"}});(with quotes "/Best*/")

这是主要问题吗?或者我做了什么愚蠢的错误?

Aks*_*hat 11

有两种类型的语法:

Polls_Coll.find({question:/Best*/});
Run Code Online (Sandbox Code Playgroud)

Polls_Coll.find({question:{$regex:"Best*"}});
Run Code Online (Sandbox Code Playgroud)

你已经在每个元素中使用了元素,这可能就是它无法工作的原因.有关mongodb文档的详细信息:http://docs.mongodb.org/manual/reference/operator/query/regex/

这两种形式在Meteor中都可以正常工作,所以你不应该对它们有任何问题.


小智 7

我使用这种语法,它对我有用:

Polls_Coll.find({ name: {$regex: "adc", $options: '-i'} });
Run Code Online (Sandbox Code Playgroud)

它类似于:

SELECT * FROM Polls_Coll WHERE name LIKE '%adc%'
Run Code Online (Sandbox Code Playgroud)

我也使用https://atmospherejs.com/meteor/reactive-var与下面的代码实现:

if (Meteor.isServer) {
    Meteor.publish('customersSearch', function(searchValue){
        if (searchValue) {
            return Customers.find({ name: {$regex: searchValue, $options: '-i'} });
        }
   });
}

var searchQuery = new ReactiveVar();

Template.NewRO.onCreated(function(){
    var self = this;
    self.autorun(function() {
        self.subscribe('vehicles');
        self.subscribe('customersSearch', searchQuery.get());
    });
});
Run Code Online (Sandbox Code Playgroud)