Prisma ClientBasic Data Access

Writing Data (JavaScript)

Overview

The Prisma client is based on the operations defined in the GraphQL schema of your Prisma API. For writing data, it basically mirrors the GraphQL mutations of your Prisma service.

For this page, we'll assume your Prisma API is based on the following datamodel:

type Link {
  id: ID! @unique
  createdAt: DateTime!
  description: String!
  url: String!
  postedBy: User
  votes: [Vote!]!
}

type User {
  id: ID! @unique
  name: String!
  email: String! @unique
  password: String!
  links: [Link!]!
  votes: [Vote!]!
}

type Vote {
  id: ID! @unique
  link: Link!
  user: User!
}

For each model type in your datamodel, six methods for writing data are generated. These are named after the mutations in the GraphQL schema, e.g. for the User model:

  • createUser: Creates a new User record in the database
  • updateUser: Updates an existing User record in the database
  • deleteUser: Deletes an existing User record from the database
  • upsertUser: Updates an existing or create a new User record in the database
  • updateManyUsers: Updates many existing User records in the database at once.
  • deleteManyUsers: Deletes many existing User records from the database at once.
  • You can view what the generated GraphQL schema for the API here
  • You can view what the generated JavaScript client here.

Each invokation of one of these methods is executed as a transaction, meaning it is either guaranteed to succeed entirely or be rolled back if it partially fails.

Creating objects

When creating new records in the database, the create-method takes one input object which wraps all the scalar fields of the record to be created. It also provides a way to create relational data for the model, this can be supplied using nested object writes.

Each method call returns an object that contains all the scalar fields of the model that was just created.

  • View the type of the input object of createLink here
  • View the type of the input object of createUser here
  • View the type of the input object of createVote here

Examples

Create a new user:

JavaScript
GraphQL
const newUser = await prisma
  .createUser({
    name: "Alice",
    email: "alice@prisma.io",
    password: "IlikeTurtles"
  })
Copy

Create a new vote:

JavaScript
GraphQL
const newVote = await prisma
  .createVote({
    user: {
      connect: {
        email: "alice@prisma.io"
      }
    },
    link: {
      connect: {
        id: "cjli47wr3005b0a23m9crhh0e"
      }
    }
  })
Copy

Create a new user with two new links:

JavaScript
GraphQL
const newUserWithLinks = await prisma
  .createUser({
    name: "Alice",
    email: "alice@prisma.io",
    password: "IlikeTurtles",
    links: {
      create: [{
        description: "My first link",
        url: "https://www.prisma.io"
      }, {
        description: "My second link",
        url: "https://www.howtographql.com"
      }]
    }, 
  })
Copy

Updating objects

When updating existing records in the database, the update-method receives one input object with two fields:

  • data: This is similar to the input object you provide to a create-method. It wraps scalar fields of the model to be updated and lets you provide relational data via nested object writes.
  • where: This is used to select the record that should be updated. You can use any unique field to identify the record.
  • data

    • View the type of the data field of updateLink here
    • View the type of the data field of updateUser here
    • View the type of the data field of updateVote here
  • where

    • View the type of the where field of updateLink here
    • View the type of the where field of updateUser here
    • View the type of the where field of updateVote here

Each method call returns an object that contains all the scalar fields of the model that was just updated.

Examples

Set a new name on an existing user:

JavaScript
GraphQL
const updatedUser = await prisma
  .updateUser({
    data: {
      name: "Alice"
    },
    where: {
      id: "cjli512bd005g0a233s1ogbgy"
    }
  })
Copy

Update a link so that it was posted by a different user than before:

JavaScript
GraphQL
const updatedLink = await prisma
  .updateLink({
    data: {
      postedBy: {
        connect: {
          id: "cjli512bd005g0a233s1ogbgy"
        }
      },
    },
    where: {
      id: "cjli47wr3005b0a23m9crhh0e"
    }
  })
Copy

Delete the user that made a vote:

JavaScript
GraphQL
const updatedVote = await prisma
  .updateVote({
    data: {
      user: {
        delete: true
      },
    },
    where: {
      id: "cjli5aual005n0a233ekv89o4"
    }
  })
Copy

For this operation to succeed, the user field on the Vote model must not be required. Otherwise the constraint that every Vote needs to be connected to a User would be violated.

Deleting objects

When deleting records from the database, the delete-method receives one input object that specifies which record is to be deleted. The type of this input object is identical to the where object in update-methods.

The properties of that object correspond to those fields of the model that are marked as unique. For the example datamodel above, this means that for User, Vote and Link it has an id property. For User it additionally accepts the email field.

  • View the type of the input object of deleteLink here
  • View the type of the input object of deleteUser here
  • View the type of the input object of deleteVote here

Each method call returns an object that contains all the scalar fields of the model that was just deleted.

Examples

Delete a link by its id:

JavaScript
GraphQL
const deletedLink = await prisma
  .deleteLink({
    id: "cjli47wr3005b0a23m9crhh0e"
  })
Copy

Delete a user by their email:

JavaScript
GraphQL
const deletedUser = await prisma
  .deleteUser({
    email: "alice@prisma.io"
  })
Copy

Creating or updating objects (upserts)

Upsert operations allow you to try to update an existing record. If that record actually does not exist yet, it will be created. The upsert-methods are a mix of create- and update-methods, meaning they receive an input argument that has three fields:

  • where: Identical to the where field provided in update-methods
  • update: Identical to the data field provided in update-methods
  • create: Identical to the input object provide in create-methods

Examples

Update the URL of a link. If the link doesn't exist yet, create a new one:

JavaScript
GraphQL
const updatedOrCreatedLink = await prisma
  .upsertLink({
    where: {
      id: "cjli47wr3005b0a23m9crhh0e"
    },
    update: {
      url: "https://www.howtographql.com"
    },
    create: {
      url: "https://www.howtographql.com",
      description: "Fullstack GraphQL Tutorial"
    }
  })
Copy

Updating and deleting many records

The Prisma client API offers special methods to update or delete many records at once. The corresponding mutations in the generated GraphQL API of your Prisma service are called batch mutations. Each updateMany- and deleteMany-method only returns the number of records that ultimately have been affected by the operation.

Examples

Update three links, specified by their IDs, and reset their URLs to the empty string:

JavaScript
GraphQL
const updatedLinksCount = await prisma
  .updateManyLinks({
    where: {
      id_in: ["cjli6tknz005s0a23uf0lmlve", "cjli6tnkj005x0a2325ynfpb9", "cjli6tq3200620a23s4lp8npd"]
    },
    data: {
      url: ""
    },
  }).count
Copy

If one or more of the provided IDs do not actually exist in the database, the operation will not return an error.

Update all links where the description contains the string graphql and reset their URLs to the empty string:

JavaScript
GraphQL
const updatedLinksCount = await prisma
  .updateManyLinks({
    where: {
      description_contains: "graphql"
    },
    data: {
      url: ""
    },
  }).count
Copy

Delete all links that were created before 2018:

JavaScript
GraphQL
const deleteLinksCount = await prisma
  .deleteManyLinks({
    createdAt_lte: "2018"
  }).count
Copy

Nested object writes

Nested object writes let you modify database records across multiple models in a single transaction. The corresponding concept from Prisma GraphQL API is called nested mutations. Nested object writes are available for create- and update-methods.

If a model has a relation to a different model, the corresponding relation field is set with an object that has a subset of the following properties:

  • create: Creates a new record of the related model and connects it via the relation.
  • update: Updates an existing record of the related model that is already connected via the relation.
  • upsert: Updates an existing record of the related model or creates and connects a new one.
  • delete: Deletes an existing record of the related model that is connected via the relation.
  • connect: Connects an existing record of the related model via the relation.
  • disconnect: Deletes an existing record of the related model via the relation.

Examples

Create a new user with two new links and connect one existing link:

JavaScript
GraphQL
const newUserWithLinks = await prisma
  .createUser({
    name: "Alice",
    email: "alice@prisma.io",
    password: "IlikeTurtles",
    links: {
      create: [{
        description: "My first link",
        url: "https://www.prisma.io"
      }, {
        description: "My second link",
        url: "https://www.howtographql.com"
      }],
      connect: {
        id: "cjli6tknz005s0a23uf0lmlve"
      }
    }, 
  })
Copy

Delete a link from a user:

JavaScript
GraphQL
const updatedUser = await prisma
  .updateUser({
    where: {
      id: "cjli8znnd006n0a23ywc6wf8w"
    },
    data: {
      links: {
        delete: {
          id: "cjli6tknz005s0a23uf0lmlve"
        }
      }
    }
  })
Copy