/
index.js
70 lines (54 loc) · 1.43 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// mongoose-keywordize
module.exports = exports = function keywordize (schema, options) {
if (!Array.isArray(options.fields)) options.fields = [options.fields];
var fields = options.fields.slice()
, fn = 'function' == typeof options.fn && options.fn
schema.add({ keywords: [String] });
/**
* Keywordize.
*
* Breaks apart field values into separate keywords.
* @return {MongooseArray}
* @api public
*/
schema.methods.keywordize = function () {
var self = this;
var values = fields.map(function (field) {
return self.get(field);
});
if (fn) {
var res = fn.call(self);
if (undefined !== res) {
if (!Array.isArray(res)) res = [res];
values = values.concat(res);
}
}
this.set('keywords', []);
var keywords = this.keywords;
var i = values.length;
while (i--) {
;(values[i] || '').split(/\s/).forEach(function (word) {
word = word.trim();
if (word) keywords.addToSet(word);
})
}
return keywords;
}
/**
* Update the keywords if any field changed.
*/
schema.pre('save', function (next) {
var self = this;
var changed = this.isNew || fields.some(function (field) {
return self.isModified(field);
});
if (changed) this.keywordize();
next();
});
}
/**
* Expose version.
*/
exports.version = JSON.parse(
require('fs').readFileSync(__dirname + '/../package.json')
).version;