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()

Differences to connectors for relational databases

This section covers ways in which the MongoDB connector differs from Prisma connectors for relational databases.

No support for Prisma Migrate

Currently, there are no plans to add support for Prisma Migrate as MongoDB projects do not rely on internal schemas where changes need to be managed with an extra tool. Management of @unique indexes is realized through db push.

No support for @@id and autoincrement()

The @@id attribute (an ID for multiple fields) is not supported because primary keys in MongoDB are always on the _id field of a model.

The autoincrement() function (which creates incrementing @id values) is not supported because autoincrement() does not work with the ObjectID type that the _id field has in MongoDB.

Cyclic references and referential actions

If you have cyclic references in your models, either from self-relations or a cycle of relations between models, and you use referential actions, you must set a referential action of NoAction to prevent an infinite loop of actions.

See Special rules for referential actions for more details.

Replica set configuration

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, Prisma shows the message Error: Transactions are not supported by this deployment. The full text of the error message is 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.

Native type mapping from Prisma to MongoDB

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