Working with Create Operations
1. Creating Single Record
const user = await prisma.user.create({
data: { email: "a@b.io", name: "Alice" }
});
| Option | Use |
data | Field values |
select | Return projection |
include | Include related records |
2. Creating with Nested Relations
await prisma.user.create({
data: {
email: "a@b.io",
posts: {
create: [
{ title: "Hello", published: true },
{ title: "World" }
]
}
}
});
| Nested Op | Effect |
create | New related rows |
connect | Link existing rows |
connectOrCreate | Link or insert |
createMany | Bulk insert children |
3. Creating Multiple Records
const result = await prisma.user.createMany({
data: [{ email: "a@b.io" }, { email: "c@d.io" }],
skipDuplicates: true
});
console.log(result.count);
| Aspect | Detail |
| Returns | Count of inserted rows |
| No nested | Cannot create relations |
| Mongo | Supported |
| SQLite | Supported in Prisma 5.12+ |
4. Using skipDuplicates Option
| Behavior | Detail |
| Effect | Skip rows that violate unique constraint |
| DBs | PG, MySQL (uses ON CONFLICT/INSERT IGNORE) |
| Use case | Idempotent bulk insert |
5. Creating with Select
const user = await prisma.user.create({
data: { email: "a@b.io" },
select: { id: true, email: true }
});
| Aspect | Detail |
| Reduces payload | Only listed fields returned |
| Type | Narrow inferred type |
6. Creating with Include
| Option | Effect |
include | Add related records to result |
| Conflict | Cannot combine with select at same level |
7. Applying Default Values
| Source | Behavior |
| Schema | @default applied when field omitted |
| DB-side | dbgenerated functions executed at insert |
8. Handling Unique Violations
try {
await prisma.user.create({ data: { email: "dup@x.io" } });
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") {
// unique constraint failed on e.meta?.target
}
}
| Code | Meaning |
P2002 | Unique constraint failed |
P2003 | FK violation |
9. Connecting Existing Relations
await prisma.post.create({
data: { title: "Hi", author: { connect: { id: 1 } } }
});
| Pattern | Use |
| connect by unique | Use any unique field (e.g., email) |
| composite | Use compound unique key shape |
10. Using connectOrCreate Pattern
await prisma.post.create({
data: {
title: "Hi",
tags: {
connectOrCreate: [
{ where: { name: "react" }, create: { name: "react" } },
{ where: { name: "ts" }, create: { name: "ts" } }
]
}
}
});
| Aspect | Detail |
| Idempotent | Safe to retry |
| Where | Must reference unique constraint |