#Using slug as _id

3 messages · Page 1 of 1 (latest)

pure sun
#

I'm trying to create an app that has SEO at the forefront and so will need to have readable URLs, is it better to have a separate "slug" field on the document and then have to use ctx.db.query to get the item; or create my own "_id" field so that I can directly use ctx.db.get to request the specific item?

balmy lotusBOT
#

Hi @pure sun. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Convex, the _id field is automatically generated by the system and it must be the one allocated by Convex. You cannot customize it with your own id or slug (source (https://discord.com/channels/1019350475847499849/1251450710520893500)).

However, you can use another field, such as slug or myAppId, to store your custom id or slug. If you define an index on that field, the performance of fetching a document by your custom id or slug is identical to using db.get with the _id field (source (https://discord.com/channels/1019350475847499849/1251450710520893500)).

Here's an example of how you might query a document by a custom slug field:

const document = await ctx.db
  .query("documents")
  .withIndex("by_slug", q => q.eq("slug", "my-custom-slug"))
  .first();

In this example, "documents" is the name of the table, "by_slug" is the name of the index on the slug field, and "my-custom-slug" is the specific slug you're querying for.

Remember to create an index on the slug field in your schema for optimal performance.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: