Back to Prisma1

01 Setting Up Prisma Existing Database JAVASCRIPT A003

docs/1.31/get-started/01-setting-up-prisma-existing-database-JAVASCRIPT-a003.mdx

1.34.126.9 KB
Original Source

import Warning from 'components/Markdown/Warning' import QueryChooser from 'components/Markdown/QueryChooser' import Code from 'components/Markdown/Code' import Collapse from 'components/Markdown/Collapse'

export const meta = { title: 'Set up Prisma', position: 1, gettingStartedOrder: 2, gettingStartedTitle: 'Existing database', nextText: 'Great work! 👏 Move on to learn how you can extend your datamodel and make changes to your Prisma API.', technology: 'node', technologyOrder: 1, articleGroup: 'Set up Prisma', }

Goals

On this page, you will learn how to:

  • Install the Prisma CLI
  • Set up Prisma using Docker
  • Introspect your existing database and derive a datamodel
  • Use the datamodel to configure your Prisma API
  • Generate a Prisma client
  • Read and write data using the Prisma client

Install the Prisma CLI

The Prisma CLI is used for various Prisma workflows. You can install it using Homebrew or NPM:

<Code languages={["Homebrew", "NPM"]}>

bash
brew tap prisma/prisma
brew install prisma
bash
npm install -g prisma
</Code>

Install Docker

To use Prisma locally, you need to have Docker installed on your machine. If you don't have Docker yet, you can download the Docker Community Edition for your operating system here.

Set up Prisma

Run the following command to connect Prisma to your existing database:

bash
prisma init hello-world

This launches an interactive wizard. Here's what you need to do:

  1. Select Use existing database
  2. Select your database, either MySQL, PostgreSQL or MongoDB
  3. Provide the connection details for your database (see below for more info)
  4. Select the Prisma JavaScript client
<Collapse title="Connection details for MySQL & PostgreSQL">
  • The host of your DB server, e.g. localhost. (When connecting to a local database, you might need to use host.docker.internal.)
  • The port where your DB server listens, e.g. 5432 (PostgreSQL) or 3306 (MySQL).
  • The name of your database.
  • Only PostgreSQL: The name of your PostgreSQL schema, e.g. public.
  • The DB user.
  • The password for the DB user.
  • Whether your database server uses SSL, possible values are true and false.
</Collapse> <Collapse title="Connection details for MongoDB">
  • Your MongoDB connection string, e.g. http://user1:myPassword@localhost:27017/admin. Note that this must include the database credentials as well as the authSource database that's storing the credentials of your MongoDB admin user (by default it is often called admin). Learn more here.
  • The name of your MongoDB database.

If you're using MongoDB Atlas, you can find your connection string by clicking the CONNECT-button on your cluster overview page. It looks similar to this: mongodb+srv://user:[email protected]/test?retryWrites=true.

</Collapse>

Launch Prisma

To start Prisma and connect it to your database, run the following commands:

bash
cd hello-world
docker-compose up -d

Prisma is now connected to your database and runs on http://localhost:4466.

<Collapse title="Securing your Prisma server">

The Prisma server is currently unprotected, meaning everyone with access to its endpoint can send arbitrary requests to it. To secure the Prisma server, you need to set the managementApiSecret property in your Docker Compose file when deploying the server.

When using the Prisma CLI, you then need to set the PRISMA_MANAGEMENT_API_SECRET to the same value so that the CLI can authenticate against the secured server. Learn more here.

</Collapse>

Deploy the Prisma datamodel

You now have the minimal setup ready to deploy your Prisma datamodel. Run the following command (this does not change anything in your database):

bash
prisma deploy
<Warning>

Launching the Prisma server may take a few minutes. In case the prisma deploy command fails, wait a few minutes and try again. Also run docker ps to ensure the Prisma Docker container is actually running.

</Warning>

View and edit your data in Prisma Admin

If you want to view and edit the data in your database, you can use Prisma Admin. To access Prisma Admin, you need to append /_admin to your Prisma endpoint, for example: http://localhost:4466/_admin.

Prepare Node application

Run the following command to create an empty Node script:

bash
touch index.js

Next, initialize an empty NPM project in the current directory and install the required dependencies:

bash
npm init -y
npm install --save prisma-client-lib

Read and write data using the Prisma client

The API operations of the Prisma client depend on the datamodel that was generated from the database introspection. The following sample queries assume there is a User type in the datamodel defined as follows:

graphql
type User {
  id: ID! @id
  name: String!
}

If you don't have such a User type, you need to adjust the following code snippets with a type that matches your datamodel.

Add the following code in index.js:

js
const { prisma } = require('./generated/prisma-client')

// A `main` function so that we can use async/await
async function main() {

  // Create a new user called `Alice`
  const newUser = await prisma.createUser({ name: 'Alice' })
  console.log(`Created new user: ${newUser.name} (ID: ${newUser.id})`)

  // Read all users from the database and print them to the console
  const allUsers = await prisma.users()
  console.log(allUsers)
}

main().catch(e => console.error(e))

Execute the script with the following command:

bash
node index.js

Whenever you run this script with that command, a new user record is created in the database (because of the call to createUser).

Feel free to play around with the Prisma client API and try out some of the following operations by adding the following code snippets to the file (at the end of the main function) and re-executing the script:

<QueryChooser titles={["Fetch single user", "Filter user list", "Update a user's name", "Delete user"]}>

js
const user = await prisma
  .user({ id: '__USER_ID__' })
js
const usersCalledAlice = await prisma
  .users({
    where: {
      name: 'Alice'
    }
  })
js
 const updatedUser = await prisma
  .updateUser({
    where: { id: '__USER_ID__' },
    data: { name: 'Bob' }
  })
js
 const deletedUser = await prisma
  .deleteUser({ id: '__USER_ID__' })
</QueryChooser>

In some snippets, you need to replace the __USER__ID__ placeholder with the ID of an actual user.