如何使用Postgres与TypeORM生成唯一Slug(重复标题自动加后缀)
生成唯一Slug并处理重复场景的实现方案
需求说明
- 从前端接收
title字段(如{title: "this is the blog title"}),转换为格式如this-is-the-blog-title的Slug - 若该Slug已存在,新文档需生成带递增数字后缀的唯一Slug,例如
this-is-the-blog-title-1、this-is-the-blog-title-2……
现有代码问题
当前代码仅检查基础Slug是否存在,重复时无法自动生成递增后缀,需要补充查询已存在的带后缀Slug并计算最新序号的逻辑。
实现代码
const slugTitle = slugify(this.title); // 查询所有匹配基础Slug及带数字后缀的Slug let existingSlugs = await this.model.find( { slug: { $regex: new RegExp(`^${slugTitle}(-\\d+)?$`) } }, { slug: 1 } ); if (existingSlugs.length === 0) { // 无匹配记录,直接使用基础Slug await this.model.create({ slug: slugTitle }); } else { // 提取所有带后缀的数字,找出最大值 let maxSuffix = 0; existingSlugs.forEach(item => { const match = item.slug.match(new RegExp(`${slugTitle}-(\\d+)`)); if (match) { const suffix = parseInt(match[1], 10); maxSuffix = Math.max(maxSuffix, suffix); } }); // 生成新的唯一Slug const newSlug = maxSuffix === 0 ? `${slugTitle}-1` : `${slugTitle}-${maxSuffix + 1}`; await this.model.create({ slug: newSlug }); }
优化提示
- 给
slug字段添加唯一索引,避免并发场景下可能出现的重复插入问题 - 高并发场景下,建议结合数据库事务或乐观锁机制,进一步保证Slug的唯一性
内容的提问来源于stack exchange,提问作者Md Ali
相关产品推荐
相关产品推荐

