#unique

3 messages · Page 1 of 1 (latest)

wintry bluff
#

How do i create a unique compound key in a table in convex?

swift marlinBOT
#

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

#

In Convex, you can create a unique compound key in a table by defining an index on the fields you want to make unique. You can then ensure that a document with a given value doesn’t already exist anywhere you write given documents. Here's an example:

// schema.ts
yourTable: defineTable({
  field1: v.string(),
  field2: v.string(),
}),
  .index("compoundKey", ["field1", "field2"])

// myFunctions.ts
// Before every insert, patch or replace using the `field1` and `field2` fields:
const existing = await ctx.db
  .query("yourTable")
  .withIndex("compoundKey", (q) => q.eq("field1", field1Value).eq("field2", field2Value))
  .first();
if (existing !== null) {
  throw new Error(
    `In table "yourTable" cannot create a duplicate document with field "field1" of value \`${field1Value}\` and field "field2" of value \`${field2Value}\`, existing document with ID "${
      existing._id as string
    }" already has it.`,
  );
}

In this example, field1 and field2 form the compound key. Before inserting, patching, or replacing a document, you check if a document with the same values for field1 and field2 already exists. If it does, an error is thrown.

Please note that this is a manual way of enforcing uniqueness. Convex does not currently support automatic enforcement of unique compound keys at the schema level.

For more information, you can refer to the Convex documentation (https://stack.convex.dev/ents#unique-field-values).

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