Last active
June 16, 2017 18:59
-
-
Save ifedotov/e0058da231f37a34fd0d206e93d6e78d to your computer and use it in GitHub Desktop.
Updated process for making unique slug in Learn Node course by Wes Bos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
storeSchema.pre('save', async function(next) { | |
if (!this.isModified('name')) { | |
next(); // skip it | |
return; // stop this function from running | |
} | |
var _slug = slug(this.name); | |
this.slug = _slug; | |
// find other stores that have a slug of wes, wes-1, wes-2 | |
const slugRegEx = new RegExp(`^(${_slug})((-[0-9]*$)?)$`, 'i'); | |
const storesWithSlug = await this.constructor.find({ slug: slugRegEx }); | |
if (storesWithSlug.length) { | |
var idx = 1; | |
while(storesWithSlug.find((store)=> {return store.slug === this.slug})) { | |
this.slug = `${_slug}-${storesWithSlug.length + idx++}`; | |
} | |
} | |
next(); | |
// TODO make more resiliant so slugs are unique | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment