Mongoose-keywordize Plugin
Provides keyword derivation for Mongoose documents.
Options:
fields
: an array of paths you want watched and converted into keywordsfn
: optional function to execute when keywordize() runs; if a value is returned it is included in the keywords arraypre
: optional function to run against each value returned from eachfield
before it's parsed and added to the keywords arraykeywordField
: the name of the field in which keywords will be stored; defaults tokeywords
upper
: true to retain letter casing. default is false (all keywords are lowercased)
Example:
var schema = name: String title: String ;schema;
This will introduce a new keywordize()
document method which detects if any of the passed fields have been modified and updates the new keywords
property appropriately.
Example:
var Person = mongoose;var me = name: 'aaron' ;me;console // ['aaron']
The keywordize
method is always called upon saving each document, auto-updating to the latest keywords.
metitle = 'Mr';me
index
Keywordize, by default, does not define an index on the "keywords" key. If you want to define an index you should use the "index" option:
var opts = {}optsindex = true
pre
To have the opportunity to pre-process field values as they're retreived by the keywordize
plugin before they are processed, pass an optional pre
function. This function, when provided, will be run against each value returned from each field
before it's parsed and added to the keywords array. The function is passed the value
and field name.
var opts = {};optsfields = 'description' 'title'opts { // remove html entities from each keyword picked from description if 'description' == field return value; else return value; }var schema = description: String title: String ;schema; var Person = mongoose;var me = name: 'aaron' ;medescription = 'Tall & Awkward';me;console // ['aaron', 'tall', 'awkward']
fn
One may also pass an optional function to run custom logic within the call to keywordize
. The optional function will be executed within the context of the document, meaning we have access to the documents properties through the this
keyword to perform any custom logic necessary.
var opts = {};optsfields = 'name' 'title'opts { if 'Mister' === thistitle return 'Mr'; }var schema = name: String title: String ;schema; var Person = mongoose;var me = name: 'aaron' ;metitle = 'Mister';me;console // ['aaron', 'Mister', 'Mr']
Either a an Array
or single string may be returned from the function and will be pushed onto the keywords array.
upper
By default mongoose-keywordize lowercases the keywords. To preserve casing pass the upper: true
option.
Mongoose Version
>= 2.x