Installation
1
Install the MongoDB driver
- npm
- pnpm
- yarn
- bun
2
Configure the adapter
Import
mongodbAdapter from better-auth/adapters/mongodb. Pass a Db instance and, optionally, the MongoClient to enable transactions:auth.ts
Configuration options
ThemongodbAdapter function accepts a Db instance and an optional config object:
Schema and migrations
MongoDB is schemaless — Better Auth creates collections automatically as data is written. There is nogenerate or migrate step required.
Better Auth uses the following collection names by default:
user, session, account, and verification. Collection names match the model names defined in your auth config.Indexes
MongoDB does not enforce uniqueness or index constraints automatically. For optimal performance and data integrity, create the following indexes:Experimental joins
Enabling joins allows Better Auth to use MongoDB$lookup aggregations to fetch related data in a single query instead of multiple round-trips.
auth.ts