Search code examples
mongodbmeteorfull-text-searchmeteor-accounts

Username full text search in Meteor.users


I am trying to search the meteor.users collection by username.

I have followed all the steps detailed here, but I can't seem to make it work meteor.users.

Here is the code I have for that:

On Server Startup:

Meteor.startup(function(){
  Meteor.users._ensureIndex({
    "username":"text",
  });
});

In my publish function:

Meteor.publish("Meteor.users.userSearch",function(searchVal){

  if(!searchVal){
   return Meteor.users.find({});
  }

  return Meteor.users.find({$text:{$search:searchVal}});

});

On the client:

Template.foo.helpers({
  users(){
    var searchValue = Session.get('searchVal');
    Meteor.subscribe('Meteor.users.userSearch',searchValue);
    return Meteor.users.find({});
  }
});

Can someone please help me figure out what is wrong with the above?

When there is no searchValue, it works correctly and all the users are returned. As soon as there is any search value, no users are returned at all.

I have also tried directly in the mongodb console db.users.find({$text:{$search:"some_test"}}) and again there is no collection object returned.


Solution

  • You do not need to do full text search if you just want to search value of only one field (username in this case). Using normal find command with Regex value as search value is better in this case:

    Meteor.users.find({
      username: new RegExp('user1', 'gi'),
    });