The MongoDB data source connector connects Prisma to a hosted MongoDB instance.

If you'd like to be kept up to date on the latest updates and stories about the Prisma MongoDB Connector, sign up here.

Example

To connect to a MongoDB server, you need to configure a datasource block in your Prisma schema file:

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

The fields passed to the datasource block are:

The MongoDB database connector uses transactions to support nested writes. Transactions requires a replica set deployment. The easiest way to deploy a replica set is with Atlas. It's free to get started.

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

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

Connection details

Connection URL

The MongoDB connection URL can be configured in different ways depending on how you are hosting your database. The standard configuration is made up of the following components:

Structure of the MongoDB connection URL

Base URL and path

The base URL and path sections of the connection URL are made up of your authentication credentials followed by the host (and optionally, a port number) and database.

mongodb://USERNAME:PASSWORD@HOST/DATABASE

The following components make up the base URL of your database:

NamePlaceholderDescription
UserUSERNAMEName of your database user, e.g. janedoe
PasswordPASSWORDPassword for your database user
HostHOSTThe host where a mongod instance is running. If you are running a sharded cluster this will a mongos instance. This can be a hostname, IP address or UNIX domain socket.
PortPORTPort on which your database server is running, e.g. 1234. If none is provided the default 27017 is used.
DatabaseDATABASEName of the database to use. If none is specified but the authSource option is set then the authSource database name is used. If neither the database in the connection string nor the authSource option is specified then it defaults to admin

You must percentage-encode special characters.

Arguments

A connection URL can also take arguments. The following example sets three arguments:

  • An ssl connection
  • A connectTimeoutMS
  • And the maxPoolSize
mongodb://USERNAME:PASSWORD@HOST/DATABASE?ssl=true&connectTimeoutMS=5000&maxPoolSize=50

Refer to the MongoDB connection string documentation for a complete list of connection string arguments. There are no Prisma-specific arguments.

Using ObjectId

It is common practice for the _id field of a MongoDB document to contain an ObjectId:

{
"_id": { "$oid": "60d599cb001ef98000f2cad2" },
"createdAt": { "$date": { "$numberLong": "1624611275577" } },
"email": "ella@prisma.io",
"name": "Ella",
"role": "ADMIN"
}

Any field (most commonly IDs and relation scalar fields) that maps to an ObjectId in the underlying database:

  • Must be of type String or Bytes
  • Must include the @db.ObjectId attribute
  • Can optionally use @default(dbgenerated()) to auto-generate a valid ObjectId
model User {
id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
// Other fields
}
model User {
id Bytes @id @default(dbgenerated()) @map("_id") @db.ObjectId
// Other fields
}

See also: Defining ID fields in MongoDB

Generating ObjectId

To generate a valid ObjectId (for testing purposes or to manually set an ID field value), use the bson package.

npm install --save bson
import { ObjectId } from 'bson'
const id = new ObjectId()

Known limitations

As MongoDB support is currently in preview there are some known limitations that come with adopting Prisma into your MongoDB project, these include:

Troubleshooting

Error: Transactions are not supported by this deployment

MongoDB only allows you to start a transaction on a replica set. Prisma uses transactions internally to avoid partial writes on nested queries. This means we inherit the requirement of needing a replica set configured.

When you try to use Prisma's MongoDB connector on a deployment that has no replica set configured, you can experience an error message as the following:

PrismaClientUnknownRequestError2 [PrismaClientUnknownRequestError]:
Invalid `prisma.post.create()` invocation in
/index.ts:9:21
6 await prisma.$connect()
7
8 // Create the first post
→ 9 await prisma.post.create(
Error in connector: Database error. error code: unknown, error message: Transactions are not supported by this deployment
at cb (/node_modules/@prisma/client/runtime/index.js:34804:17)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
clientVersion: '2.xx.0'
}

To resolve this, we suggest you change your deployment to one with a replica set configured.

One simple way for this is to use use MongoDB Atlas to launch a free instance that has replica set support out of the box.

There's also an option to run the replica set locally with this guide: https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set

Edit this page on GitHub