javascript - Generate a unique slug on mongoose schema.pre.('update') -
i want generate slug when update called in mongoose, have , works.
schema.pre('update', function (next) { const title = this._update.$set['title'] this._update.$set['slug'] = slugify(title.tolowercase()) next() })
the problem slug unique: true field if add 2 posts same title error, example this:
"slug: post-2\" exists."
so before calling next() want sure if slug exists calling find, have code:
.pre('update', function (next) { const title = this._update.$set['title'] this._update.$set['slug'] = slugify(title.tolowercase()) this._find({ slug }, function (err, docs) { if (err) console.log(err) else console.log(docs) next() }) })
but when called following error:
? callback(null, docs) ^ typeerror: callback not function
how should continue?
try this
// uniq slug generator function, converts `text` `text1` if `text` exists schema.statics.generateslug = function(text, suffix, callback){ var _this = this; var possibletext = text + (suffix || ''); _this.findone({ slug: slugify(possibletext.tolowercase()) }, function(err, item){ if(!err) { if(!item) { callback(possibletext); } else { return _this.generateslug(text, (suffix || 0) + 1, callback); } } else { callback(null); } }); }; schema.pre('update', function (next) { var _this = this; const title = _this._update.$set['title']; _this.generateslug(title, null, function(possibleslug) { if (possibleslug) { _this._update.$set['slug'] = possibleslug; next(); } else return next(new error('no possible slug')); }); })
Comments
Post a Comment