Hey all, I’m using Autoforms, and they’re fantastic. But now I have to search for form input, and… it seems rather manual.
Is there some package that solves this?
I have 5 input parameters, which are all optional. I’m searching for First, Last, Email, Phone, Company.
So how can I do a Collection search based on 1,2,3,4 or all 5 of these parameters, case non-sensitive?
After a pretty cursory look, it looks like the most mature package is easysearch
and its autosuggest tool is the only thing available for autoforms
specifically: http://matteodem.github.io/meteor-easy-search/docs/autosuggest/
It seems pretty thoughtfully written. For small documents like people profiles, it’ll be pretty effective.
To specifically answer your question, you can see how easysearch
does it, including the specific case-non-sensitive regex it uses:
selector[aggregation].push(fieldSelector);
}
});
return selector;
},
selectorPerField(field, searchString) {
const selector = {};
searchString = searchString.replace(/(\W{1})/g, '\\$1');
selector[field] = { '$regex' : `.*${searchString}.*`, '$options' : 'i'};
return selector;
},
sort(searchObject, options) {
return options.index.fields;
}
};
}
/**
In short, it does a query that resembles, for the search “Mike”:
{
$or: [
{firstName: {$regex: '.*Mike.*', $options: 'i'}}
{lastName: {$regex: '.*Mike.*', $options: 'i'}},
...
]
}
This will do. The $options: 'i'
specifier makes it case-insensitive.
Nowadays, people who make searches on lots of documents would recommend putting the search in a method call. That’s a pretty intuitive approach. The most meteoric would be to put the search in a subscription, but make it non reactive (or at least not ordered).
2 Likes
Fantastic answer, thank you. I’ve got my script working.
if we could redo our project, one of the things we’d do different is to NOT use autoforms
for search, across multiple fields you can create a full-text index on the collection in Mongodb