forked from yields/mongoose-slug
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
50 lines (44 loc) · 1.13 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
/**
* deps
*/
var slug = require('slug-component');
/**
* slug plugin.
*
* Usage:
*
* mySchema.plugin(slug('title'));
*
* Options:
*
* - `.replace` characters to replace defaulted to `[^a-zA-Z]`
* - `.separator` separator to use, defaulted to `-`
* - `required` whether a slug is required, defaults to `true`
*
* @param {String} prop
* @param {Object} options
* @return {Function}
*/
module.exports = function(prop, opts){
return (function slugize(schema){
var title;
schema.add({ slug: String });
schema.pre('save', function(next){
var self = this;
if (prop && Array.isArray(prop)) {
var titles = [];
prop.forEach(function(el){
titles.push(self[el]);
});
title = titles.join(' ');
} else {
title = this[prop || 'title'];
}
var require = (opts && !opts.required) ? false : true
, presets = (opts && opts.override) ? true : false;
if (require && !title) return next(new Error(prop + ' is required to create a slug'));
if (title && !presets) self.slug = slug(title, opts);
next();
});
});
};