Skip to content

Commit 45869a4

Browse files
author
Farhan Hasin Chowdhury
committed
Implemented findOneAndUpdate middleware
1 parent 359968d commit 45869a4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

lib/simple-slugify.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,27 @@ module.exports = function (schema) {
2929

3030
next();
3131
});
32+
33+
schema.pre(['findOneAndUpdate'], async function (next) {
34+
const regex = /[&/\\#,+()$~%.'":*?<>{} ]/g;
35+
36+
let slug = this.get(this.schema.tree.slug.source)
37+
.toString()
38+
.toLowerCase()
39+
.trim()
40+
.replace(regex, '-');
41+
42+
try {
43+
slug = (await this.model.exists({ slug }))
44+
? `${slug}-${crypto.randomBytes(5).toString('hex')}`
45+
: slug;
46+
} catch (error) {
47+
// eslint-disable-next-line no-console
48+
console.log(error);
49+
}
50+
51+
this.set({ slug });
52+
53+
next();
54+
});
3255
};

0 commit comments

Comments
 (0)