Skip to content

Instantly share code, notes, and snippets.

@pavel-shvetsov
Last active September 1, 2015 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavel-shvetsov/255d0f105f245c1435f3 to your computer and use it in GitHub Desktop.
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
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