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

To connect Prisma with MongoDB, refer to our Getting Started documentation.

Example

To connect to a MongoDB server, configure the 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 require a replica set deployment. The easiest way to deploy a replica set is with Atlas. It's free to get started.

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(auto()) to auto-generate a valid ObjectId on document creation
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
// Other fields
}
model User {
id Bytes @id @default(auto()) @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) in your application, use the bson package.

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

Considerations

There are some considerations that come with adopting Prisma into your MongoDB project, these include:

  • Currently no plans to add support for Prisma Migrate as MongoDB projects don't rely on internal schemas where changes need to be managed with an extra tool
    • Management of @unique indexes is realized through db push
  • @@id and auto-increment are not supported.

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: '3.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 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

Type mapping between MongoDB and the Prisma schema

Alternatively, see the Prisma schema reference for type mappings organized by Prisma type.

Mapping from Prisma to MongoDB types on migration

The MongoDB connector maps the scalar types from the Prisma data model to MongoDB's native column types as follows:

PrismaMongoDB
Stringstring
Booleanbool
Intint
BigIntlong
Floatdouble
DecimalCurrently unsupported
DateTimetimestamp
Datedate
BytesbinData
Json

MongoDB types that are currently unsupported:

  • Decimal128
  • Undefined
  • DBPointer
  • Null
  • Symbol
  • MinKey
  • MaxKey
  • Object
  • Javascript
  • JavascriptWithScope
  • Regex

Mapping from MongoDB to Prisma types on Introspection

When introspecting a MongoDB database, Prisma uses the relevant scalar types. Some special types also get additional native type annotations:

MongoDB (Type | Aliases)PrismaSupportedNative database type attributeNotes
objectIdString✔️@db.ObjectId

Introspection adds native database types that are not yet supported as Unsupported fields:

schema.prisma
1model Example {
2 id String @id @default(auto()) @map("_id") @db.ObjectId
3 name String
4 regex Unsupported("RegularExpression")
5}
Edit this page on GitHub