Last active
September 1, 2015 14:54
-
-
Save pavel-shvetsov/255d0f105f245c1435f3 to your computer and use it in GitHub Desktop.
Simple mongodb search with meteor by using regular expressions. It tries to match all provided fields with the provided keywords. Inspired from http://www.stephentcannon.com/2013/11/meteor-alternative-to-mongodb-full-text.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RegExp.quote = (str) -> | |
(str + "").replace /([.?*+^$[\]\\(){}|-])/g, "\\$1" | |
Meteor.Collection::search = (options, cb) -> | |
if options?.keywords?.length >= 3 and _.isString(options.keywords) and options.fields.length >= 1 | |
query = | |
'$or': [] | |
keywords = options.keywords.split " " | |
_.each keywords, (keyword) -> | |
if keyword | |
_.each options.fields, (field) -> | |
search = {} | |
search[field] = new RegExp RegExp.quote(keyword), "i" | |
query['$or'].push search | |
cb(@find query) | |
else | |
cb null | |
# Usage | |
Posts.search | |
fields:["title", "content"] | |
keywords: "dogs cats animal" | |
, (results) -> | |
if results | |
console.log results.fetch() | |
else | |
console.log "No results" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment