mirror of
https://github.com/better-auth/better-auth.git
synced 2026-10-18 11:32:15 -05:00
docs(mongo-adapter): clarify transaction setup (#11550)
This commit is contained in:
@@ -19,24 +19,44 @@ To use the MongoDB adapter, you need to install the `@better-auth/mongo-adapter`
|
||||
|
||||
## Example Usage
|
||||
|
||||
You can use the MongoDB adapter to connect to your database as follows.
|
||||
### Replica set or sharded cluster
|
||||
|
||||
Pass `client` so the adapter uses transactions by default. Use a connection string for your replica set or sharded cluster:
|
||||
|
||||
```ts title="auth.ts"
|
||||
import { betterAuth } from "better-auth";
|
||||
import { MongoClient } from "mongodb";
|
||||
import { mongodbAdapter } from "better-auth/adapters/mongodb";
|
||||
import { mongodbAdapter } from "@better-auth/mongo-adapter";
|
||||
|
||||
const client = new MongoClient("mongodb://localhost:27017/database");
|
||||
const db = client.db();
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: mongodbAdapter(db, {
|
||||
// Optional: if you don't provide a client, database transactions won't be enabled.
|
||||
client
|
||||
client,
|
||||
}),
|
||||
});
|
||||
```
|
||||
|
||||
### Standalone server
|
||||
|
||||
A standalone MongoDB server does not support transactions. Create `db` with `MongoClient` and pass it to the adapter without the `client` option:
|
||||
|
||||
```ts title="auth.ts"
|
||||
import { betterAuth } from "better-auth";
|
||||
import { MongoClient } from "mongodb";
|
||||
import { mongodbAdapter } from "@better-auth/mongo-adapter";
|
||||
|
||||
const client = new MongoClient("mongodb://localhost:27017/database");
|
||||
const db = client.db();
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: mongodbAdapter(db),
|
||||
});
|
||||
```
|
||||
|
||||
Without transactions, an earlier write may remain if a later write fails. When you move to a replica set or sharded cluster, pass `client` to enable transactions. See [MongoDB's transaction requirements](https://www.mongodb.com/docs/manual/core/transactions-production-consideration/#availability).
|
||||
|
||||
## Schema generation & migration
|
||||
|
||||
For MongoDB, we don't need to generate or migrate the schema.
|
||||
|
||||
@@ -157,9 +157,12 @@ description: Learn how to configure Better Auth in your project.
|
||||
import { client } from "@/db"; // your mongodb client
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: mongodbAdapter(client),
|
||||
database: mongodbAdapter(client.db(), { client }),
|
||||
});
|
||||
```
|
||||
|
||||
See the [MongoDB adapter guide](/docs/adapters/mongo) for standalone
|
||||
server setup.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user