Connect your database (MongoDB)

TypeScript
MongoDB

Connect your database

To connect your database, you need to set the url field of the datasource block in your Prisma schema to your database connection URL:

prisma/schema.prisma
1datasource db {
2 provider = "mongodb"
3 url = env("DATABASE_URL")
4}

In this case, the url is set via an environment variable which is defined in .env (the example uses a MongoDB Atlas URL):

.env
1DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase"

Because MongoDB is currently a preview feature, you need to explicitly define that in the generator block.

prisma/schema.prisma
1generator client {
2 provider = "prisma-client-js"
3 previewFeatures = ["mongoDb"]
4}

You now need to adjust the connection URL to point to your own database.

The format of the connection URL for your database depends on the database you use. For MongoDB, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details):

mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE

Here's a short explanation of each component:

  • USERNAME: The name of your database user
  • PASSWORD: The password for your database user
  • HOST: The host where a mongod (or mongos) instance is running
  • PORT: The port where your database server is running (typically 27017 for MongoDB)
  • DATABASE: The name of the database

As an example, for a MongoDB database hosted on MongoDB Atlas, the connection URL might look similar to this:

.env
1DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase"
Edit this page on GitHub