我正在用猫鼬存储MongoDB中博客标题中的url段代码。因此,对于用户输入相同博客标题的情况,我想要这样做,就像Wordpress如何处理它,它在弹格上附加了一个数字,并为每一个重复增加它。
示例:
另外,当从博客标题中评估的段塞是博客标题-2,并且已经有一个博客标题-2段子弹时,它将足够聪明地在后面附加-2而不是增加数字。所以它将是博客标题-2-2。
我该如何实现呢?
发布于 2017-01-13 09:50:34
我设法想出了如何自己实现它。
function setSlug(req, res, next) {
// remove special chars, trim spaces, replace all spaces to dashes, lowercase everything
var slug = req.body.title.replace(/[^\w\s]/gi, '').trim().replace(/\s+/g, '-').toLowerCase();
var counter = 2;
// check if there is existing blog with same slug
Blog.findOne({ slug: slug }, checkSlug);
// recursive function for checking repetitively
function checkSlug(err, existingBlog) {
if(existingBlog) { // if there is blog with the same slug
if(counter == 2) // if first round, append '-2'
slug = slug.concat('-' + counter++);
else // increment counter on slug (eg: '-2' becomes '-3')
slug = slug.replace(new RegExp(counter++ + '$', 'g'), counter);
Blog.findOne({ slug: slug }, checkSlug); // check again with the new slug
} else { // else the slug is set
req.body.slug = slug;
next();
}
};
}我和Wordpress玩了一会儿;发布了很多带有奇怪标题的测试博客文章,只是为了看看它是如何处理标题转换的,并且根据我的发现实现了转换标题的第一步。Wordpress:
发布于 2017-01-13 08:56:10
在您的mongooese模型中,您可以为字段提供唯一的选项:
var post = new post({
slug: {
type: String,
unique: true
}
});然后,当您保存它时,您可以验证并知道该段塞是否是唯一的,在这种情况下,您可以修改该段塞:
var post = new post({ slug: "i-am-slug"});
var tempSlug = post.slug
var slugIsUnique = true;
car counter = 1;
do{
error = post.validateSync();
if(// not unique ){ //Make sure to only check for errors on post.slug here
slugIsUnique = false;
counter++;
tempSlug = post.slug + "-" + counter;
}
}while(!slugIsUnique)
post.slug = tempSlug;
post.save((err, post) => {
// check for error or do the usual thing
});编辑:,这将不会使用博客标题2和输出博客标题2-2,但它将输出博客标题2-1,除非它已经存在。
发布于 2020-08-24 01:47:29
我发现以下代码对我有用:
总的想法是创建一个可能需要使用的弹状体数组,然后使用MongoDB的$in查询运算符来确定是否存在这些弹头。
注意:下面的解决方案使用NPM的污点。这是可选的。我也使用crytpo进行随机化,因为它具有更高的性能。这也是可选的。
private getUniqueSlug(title: string) {
// Returns a promise to allow async code.
return new Promise((resolve, reject) => {
const uniqueSlug: string = "";
// uses npm slugify. You can use whichever library you want or make your own.
const slug: string = slugify(title, { lower: true, strict: true });
// determines if slug is an ObjectID
const slugIsObjId: boolean = (ObjectId.isValid(slug) && !!slug.match(/^[0-9a-fA-F]{24}$/));
// creates a list of slugs (add/remove to your preference)
const slugs: string[] = [];
// ensures slug is not an ObjectID
slugIsObjId ? slugs.push(slug + "(1)") : slugs.push(slug);
slugs.push(slug + "(2)");
slugs.push(slug + "(3)");
slugs.push(slug + "(4)");
slugs.push(slug + "(5)");
// Optional. 3 random as fallback (crypto used to generate a random 4 character string)
for (let x = 0; x < 2; x++) {
slugs.push(slug + "(" + crypto.randomBytes(2).toString("hex") + ")");
}
// Uses a single find instance for performance purposes
// $in searches for all collections with a slug in slugs array above
const query: any = { slug: { $in: slugs } };
Collection.find(query, { slug: true }).then((results) => {
if (results) {
results.forEach((result) => {
slugs.every((s, si) => {
// If match found, remove from slugs since that slug ID is not valid.
if (s === result.slug) { slugs.splice(si, 1); return false; } else { return true; }
});
});
}
// returns first slug. Slugs are ordered by priority
if (slugs.length > 0) { resolve(slugs[0]); } else {
reject("Unable to generate a unique slug."); // Note: If no slug, then fails. Can use ObjectID as failsafe (nearly impossible).
}
}, (err) => {
reject("Find failed");
});
});
}https://stackoverflow.com/questions/41630233
复制相似问题