#unique
3 messages · Page 1 of 1 (latest)
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.