MongoDB 适配器

MongoDB 是一种流行的 NoSQL 数据库,广泛用于构建可扩展和灵活的应用。它提供了灵活的模式,使数据建模和查询变得更加容易。

【MongoDB is a popular NoSQL database that is widely used for building scalable and flexible applications. It provides a flexible schema that allows for easy data modeling and querying.】

在开始之前,请确保你已经安装并配置了 MongoDB。更多信息,请参见 MongoDB 文档

【Before getting started, make sure you have MongoDB installed and configured. For more information, see MongoDB Documentation

示例用法

【Example Usage】

你可以使用 MongoDB 适配器按如下方式连接到你的数据库。

【You can use the MongoDB adapter to connect to your database as follows.】

auth.ts
import { betterAuth } from "better-auth";
import { MongoClient } from "mongodb";
import { mongodbAdapter } from "better-auth/adapters/mongodb";

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
  }),
});

架构生成与迁移

【Schema generation & migration】

对于 MongoDB,我们不需要生成或迁移模式。

【For MongoDB, we don't need to generate or migrate the schema.】

联接(实验性)

【Joins (Experimental)】

当 Better-Auth 需要在单个查询中从多张表获取相关数据时,数据库连接(joins)非常有用。像 /get-session/get-full-organization 等端点以及许多其他端点都极大地受益于这一功能,根据数据库延迟的不同,性能提升可达 2 到 3 倍。

【Database joins is useful when Better-Auth needs to fetch related data from multiple tables in a single query. Endpoints like /get-session, /get-full-organization and many others benefit greatly from this feature, seeing upwards of 2x to 3x performance improvements depending on database latency.】

1.4.0 版本起,MongoDB 适配器开箱即用地支持连接(joins)。要启用此功能,你需要在你的认证配置中将 experimental.joins 选项设置为 true

【The MongoDB adapter supports joins out of the box since version 1.4.0. To enable this feature, you need to set the experimental.joins option to true in your auth configuration.】

auth.ts
export const auth = betterAuth({
  experimental: { joins: true }
});

附加信息

【Additional Information】

On this page