Answer the question
In order to leave comments, you need to log in
How to generate unique slug for CNC?
There is a table of posts in the database and the name and slug columns in the same place.
slug is built based on the string from name.
name="title" -> slug="title"
name="title-1" -> slug="title-1"
name="title-2" -> slug="title-2
" if the name in the name column coincided with the one that already existed when creating a new post, then the slug added a number to itself. For example:
name="title" -> slug="title"
name="title" -> slug="title-1"
name="title" -> slug="title-2"
name="title" -> slug ="title-3"
Tried different ways but without success.
mysql+nodejs stack (NestJS)
Answer the question
In order to leave comments, you need to log in
The name field must be essentially unique in your case and cannot be the same. But if for some reason this is not the case, then where you have validation before adding, check for a name match and generate using the date. Those. add not 1-2-3, but the date in the slug. As an option. After generation, you can check if there is such a slug in the database, but if you generate a slug with an accuracy of up to ms, this is very unlikely ... but you can add such a check. It's just that these are all queries to the database and it's better not to produce a lot of them.
If you still need 1-2-3, then get all records with this name, look at the maximum number in the slug and add 1.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question