Working with Create Operations

1. Creating Single Record

const user = await prisma.user.create({
  data: { email: "a@b.io", name: "Alice" }
});
OptionUse
dataField values
selectReturn projection
includeInclude 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 OpEffect
createNew related rows
connectLink existing rows
connectOrCreateLink or insert
createManyBulk 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);
AspectDetail
ReturnsCount of inserted rows
No nestedCannot create relations
MongoSupported
SQLiteSupported in Prisma 5.12+

4. Using skipDuplicates Option

BehaviorDetail
EffectSkip rows that violate unique constraint
DBsPG, MySQL (uses ON CONFLICT/INSERT IGNORE)
Use caseIdempotent bulk insert

5. Creating with Select

const user = await prisma.user.create({
  data: { email: "a@b.io" },
  select: { id: true, email: true }
});
AspectDetail
Reduces payloadOnly listed fields returned
TypeNarrow inferred type

6. Creating with Include

OptionEffect
includeAdd related records to result
ConflictCannot combine with select at same level

7. Applying Default Values

SourceBehavior
Schema@default applied when field omitted
DB-sidedbgenerated 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
  }
}
CodeMeaning
P2002Unique constraint failed
P2003FK violation

9. Connecting Existing Relations

await prisma.post.create({
  data: { title: "Hi", author: { connect: { id: 1 } } }
});
PatternUse
connect by uniqueUse any unique field (e.g., email)
compositeUse 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" } }
      ]
    }
  }
});
AspectDetail
IdempotentSafe to retry
WhereMust reference unique constraint