Skip to content

Instantly share code, notes, and snippets.

@ifedotov
Last active June 16, 2017 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ifedotov/e0058da231f37a34fd0d206e93d6e78d to your computer and use it in GitHub Desktop.
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
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