|
2 | 2 |
|
3 | 3 | const crypto = require('crypto');
|
4 | 4 |
|
5 |
| -async function makeSlug(source, doc) { |
6 |
| - const regex = /[&/\\#,+()$~%.'":*?<>{} ]/g; |
7 |
| - |
8 |
| - let slug = doc[source].toString().toLowerCase().trim().replace(regex, '-'); |
9 |
| - |
10 |
| - try { |
11 |
| - slug = (await doc.model(doc.constructor.modelName).exists({ slug })) |
12 |
| - ? `${slug}-${crypto.randomBytes(5).toString('hex')}` |
13 |
| - : slug; |
14 |
| - } catch (error) { |
15 |
| - // eslint-disable-next-line no-console |
16 |
| - console.log(error); |
17 |
| - } |
18 |
| - |
19 |
| - return slug; |
20 |
| -} |
| 5 | +const regex = /[&/\\#,+()$~%.'":*?<>{} ]/g; |
21 | 6 |
|
22 | 7 | module.exports = function (schema) {
|
23 | 8 | schema.pre(['save', 'updateOne'], async function (next) {
|
24 | 9 | const { source } = schema.tree.slug;
|
25 | 10 |
|
26 |
| - const doc = this; |
| 11 | + let slug = this[source].toString().toLowerCase().trim().replace(regex, '-'); |
| 12 | + |
| 13 | + try { |
| 14 | + slug = (await this.model(this.constructor.modelName).exists({ slug })) |
| 15 | + ? `${slug}-${crypto.randomBytes(5).toString('hex')}` |
| 16 | + : slug; |
| 17 | + } catch (error) { |
| 18 | + // eslint-disable-next-line no-console |
| 19 | + console.log(error); |
| 20 | + } |
27 | 21 |
|
28 |
| - this.slug = await makeSlug(source, doc); |
| 22 | + this.slug = slug; |
29 | 23 |
|
30 | 24 | next();
|
31 | 25 | });
|
32 | 26 |
|
33 |
| - schema.pre(['findOneAndUpdate'], async function (next) { |
34 |
| - const regex = /[&/\\#,+()$~%.'":*?<>{} ]/g; |
35 |
| - |
| 27 | + schema.pre(['update', 'findOneAndUpdate'], async function (next) { |
36 | 28 | let slug = this.get(this.schema.tree.slug.source)
|
37 | 29 | .toString()
|
38 | 30 | .toLowerCase()
|
|
0 commit comments