dynamic search with operator like in mongodb

737 Views Asked by At

I am new with Meteor and MongoDB. I want to ask how to search data dynamically in MongoDB. My attempt is:

Template.MainTemplate.ItemsFounded = function() {
    return ITEM.find({ItemName:{$regex: Session.get('SearchItemName')}});
};

Template.TemplateSearchItem.events({
    'click .SearchItem' : function() {
        var $itemName =  $('#TextboxSearchItemName');
        Session.set('SearchItemName', '/'+ $itemName.val()+ '/');
    }
});

when it runs, it display nothing.. can someone help me? sorry for my silly question..

thanks

1

There are 1 best solutions below

7
On

The problem could come from the fact that you are not building a regex but a simple String with this:

Session.set('SearchItemName', '/'+ $itemName.val()+ '/');

In order to build a regex you should create a new RegExp object to be use in the Mongo $regexquery. You should also rewrite "ItemsFounded" as it is not the proper way to declare helpers in Meteor:

Template.TemplateSearchItem.events({
  'click .SearchItem' : function() {
    var $itemName =  $('#TextboxSearchItemName');
    Session.set('SearchItemName', $itemName.val());
  }
});
...
Template.MainTemplate.helpers({
  ItemsFounded: function() {
    var regex = new RegExp(Session.get('SearchItemName'), 'i'); //'i' for case insensitive search
    return ITEM.find({ItemName:{$regex: regex}});
  }      
});