unexpected Invalid id value error during login with mongoose #1956

Closed
opened 2026-03-13 09:15:56 -05:00 by GiteaMirror · 24 comments
Owner

Originally created by @firatciftci on GitHub (Sep 18, 2025).

Originally assigned to: @ping-maxwell on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

  1. Create a new SvelteKit application
  2. Set up Better Auth using the mongodbAdapter and Mongoose
  3. Create a form to log in using email and password
  4. Build the application
  5. Deploy and run the production application
  6. Enter credential and press the login button
  7. See error logs in production server

Current vs. Expected behavior

In Better Auth version 1.3.9 and below, signing in works without any issues. However, in version 1.3.10 and above, a sign in operation throws the following error:

2025-09-18T07:13:34.571Z ERROR [Better Auth]: Error Error: Invalid id value
    at serializeID (file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:99202:12)
    at file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:99224:30
    at Array.map (<anonymous>)
    at convertWhereClause (file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:99214:29)
    at Object.findMany (file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:99314:28)
    at Object.findMany (file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:97068:38)
    at Object.findUserByEmail (file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:98083:52)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async file:///app/build/server/chunks/better-auth.D-2CmEwz-taOnBrMS.js:10303:15
    at async internalHandler (file:///app/build/server/chunks/better-auth.D-2CmEwz-taOnBrMS.js:1138:20)

There appears to be a regression with the mongodbAdapter and how it handles MongoDB ObjectId values during the login process as it tries to serialize the value to a string.

What version of Better Auth are you using?

1.3.11

System info

{
  "system": {
    "platform": "darwin",
    "arch": "arm64",
    "version": "Darwin Kernel Version 25.0.0: Mon Aug 25 21:17:54 PDT 2025; root:xnu-12377.1.9~3/RELEASE_ARM64_T6041",
    "release": "25.0.0",
    "cpuCount": 14,
    "cpuModel": "Apple M4 Pro",
    "totalMemory": "24.00 GB",
    "freeMemory": "0.42 GB"
  },
  "node": {
    "version": "v22.19.0",
    "env": "development"
  },
  "packageManager": {
    "name": "npm",
    "version": "11.6.0"
  },
  "frameworks": [
    {
      "name": "svelte",
      "version": "^5.39.2"
    },
    {
      "name": "@sveltejs/kit",
      "version": "^2.42.1"
    }
  ],
  "databases": null,
  "betterAuth": {
    "version": "1.3.11",
    "config": {
      "plugins": [
        {
          "name": "username",
          "config": {
            "id": "username",
            "endpoints": {},
            "schema": {
              "user": {
                "fields": {
                  "username": {
                    "type": "string",
                    "required": false,
                    "sortable": true,
                    "unique": true,
                    "returned": true,
                    "transform": {}
                  },
                  "displayUsername": {
                    "type": "string",
                    "required": false,
                    "transform": {}
                  }
                }
              }
            },
            "hooks": {
              "before": [
                {},
                {}
              ]
            },
            "$ERROR_CODES": {
              "INVALID_USERNAME_OR_PASSWORD": "[REDACTED]",
              "EMAIL_NOT_VERIFIED": "Email not verified",
              "UNEXPECTED_ERROR": "Unexpected error",
              "USERNAME_IS_ALREADY_TAKEN": "Username is already taken. Please try another.",
              "USERNAME_TOO_SHORT": "Username is too short",
              "USERNAME_TOO_LONG": "Username is too long",
              "INVALID_USERNAME": "Username is invalid",
              "INVALID_DISPLAY_USERNAME": "Display username is invalid"
            }
          }
        },
        {
          "name": "sveltekit-cookies",
          "config": {
            "id": "sveltekit-cookies",
            "hooks": {
              "after": [
                {}
              ]
            }
          }
        }
      ],
      "emailAndPassword": {
        "enabled": true,
      },
    }
  }
}

Which area(s) are affected? (Select all that apply)

Backend

Auth config (if applicable)

import { getRequestEvent } from "$app/server";
import { betterAuth } from "better-auth";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { username } from "better-auth/plugins";
import { sveltekitCookies } from "better-auth/svelte-kit";
import mongoose from "mongoose";
import dbConnect from "./db-connect";

await dbConnect();
const client = mongoose.connection.db;

export const auth = betterAuth({
  database: mongodbAdapter(client),
  plugins: [username(), sveltekitCookies(getRequestEvent)],
  emailAndPassword: {
    enabled: true,
  },
});

Additional context

No response

Originally created by @firatciftci on GitHub (Sep 18, 2025). Originally assigned to: @ping-maxwell on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce 1. Create a new SvelteKit application 2. Set up Better Auth using the `mongodbAdapter` and Mongoose 3. Create a form to log in using email and password 4. Build the application 5. Deploy and run the production application 4. Enter credential and press the login button 5. See error logs in production server ### Current vs. Expected behavior In Better Auth version 1.3.9 and below, signing in works without any issues. However, in version 1.3.10 and above, a sign in operation throws the following error: ``` 2025-09-18T07:13:34.571Z ERROR [Better Auth]: Error Error: Invalid id value at serializeID (file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:99202:12) at file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:99224:30 at Array.map (<anonymous>) at convertWhereClause (file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:99214:29) at Object.findMany (file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:99314:28) at Object.findMany (file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:97068:38) at Object.findUserByEmail (file:///app/build/server/chunks/hooks.server-DX0z3Uu4.js:98083:52) at process.processTicksAndRejections (node:internal/process/task_queues:105:5) at async file:///app/build/server/chunks/better-auth.D-2CmEwz-taOnBrMS.js:10303:15 at async internalHandler (file:///app/build/server/chunks/better-auth.D-2CmEwz-taOnBrMS.js:1138:20) ``` There appears to be a regression with the `mongodbAdapter` and how it handles MongoDB ObjectId values during the login process as it tries to serialize the value to a string. ### What version of Better Auth are you using? 1.3.11 ### System info ```bash { "system": { "platform": "darwin", "arch": "arm64", "version": "Darwin Kernel Version 25.0.0: Mon Aug 25 21:17:54 PDT 2025; root:xnu-12377.1.9~3/RELEASE_ARM64_T6041", "release": "25.0.0", "cpuCount": 14, "cpuModel": "Apple M4 Pro", "totalMemory": "24.00 GB", "freeMemory": "0.42 GB" }, "node": { "version": "v22.19.0", "env": "development" }, "packageManager": { "name": "npm", "version": "11.6.0" }, "frameworks": [ { "name": "svelte", "version": "^5.39.2" }, { "name": "@sveltejs/kit", "version": "^2.42.1" } ], "databases": null, "betterAuth": { "version": "1.3.11", "config": { "plugins": [ { "name": "username", "config": { "id": "username", "endpoints": {}, "schema": { "user": { "fields": { "username": { "type": "string", "required": false, "sortable": true, "unique": true, "returned": true, "transform": {} }, "displayUsername": { "type": "string", "required": false, "transform": {} } } } }, "hooks": { "before": [ {}, {} ] }, "$ERROR_CODES": { "INVALID_USERNAME_OR_PASSWORD": "[REDACTED]", "EMAIL_NOT_VERIFIED": "Email not verified", "UNEXPECTED_ERROR": "Unexpected error", "USERNAME_IS_ALREADY_TAKEN": "Username is already taken. Please try another.", "USERNAME_TOO_SHORT": "Username is too short", "USERNAME_TOO_LONG": "Username is too long", "INVALID_USERNAME": "Username is invalid", "INVALID_DISPLAY_USERNAME": "Display username is invalid" } } }, { "name": "sveltekit-cookies", "config": { "id": "sveltekit-cookies", "hooks": { "after": [ {} ] } } } ], "emailAndPassword": { "enabled": true, }, } } } ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { getRequestEvent } from "$app/server"; import { betterAuth } from "better-auth"; import { mongodbAdapter } from "better-auth/adapters/mongodb"; import { username } from "better-auth/plugins"; import { sveltekitCookies } from "better-auth/svelte-kit"; import mongoose from "mongoose"; import dbConnect from "./db-connect"; await dbConnect(); const client = mongoose.connection.db; export const auth = betterAuth({ database: mongodbAdapter(client), plugins: [username(), sveltekitCookies(getRequestEvent)], emailAndPassword: { enabled: true, }, }); ``` ### Additional context _No response_
GiteaMirror added the sveltebug labels 2026-03-13 09:15:56 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Sep 18, 2025):

Hi @firatciftci! I'm Dosu and I’m helping the better-auth team.

This regression is caused by stricter type checks in the serializeID function of the mongodbAdapter starting in Better Auth v1.3.10. Now, any value passed as an ID (for fields like id or _id) must be a string or a MongoDB ObjectId—other types (like null, numbers, or unexpected objects) will trigger the Invalid id value error during login and user lookup operations. This change was introduced to enforce consistency and prevent silent failures in ID handling, but it can break setups where IDs are not always strings or ObjectIds, or where custom models have mismatched or missing id fields [source].

Workaround:
You can disable Better Auth's internal ID generation by setting advanced.database.generateId: false in your auth config. This lets MongoDB generate ObjectIds automatically and prevents the adapter from trying to convert or validate IDs that aren't strings or ObjectIds [source].
Example:

export const auth = betterAuth({
  database: mongodbAdapter(client, { generateId: false }),
  plugins: [username(), sveltekitCookies(getRequestEvent)],
  emailAndPassword: { enabled: true },
});

Make sure your MongoDB documents have valid _id fields and avoid having id: null or mismatched id/_id values.

Caveat:
If your setup uses custom models or schemas, double-check that all user/account/session documents have proper _id fields and that queries do not pass unexpected types for IDs. If you use Mongoose, ensure you have the mongodb package installed, as the adapter expects ObjectId from mongodb rather than Mongoose's type [source].

If you need more granular control, you can provide a custom ID generator via advanced.database.generateId—the adapter will then skip its own conversion and use your logic directly.

Let me know if you need help with a specific model or query!

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

@dosubot[bot] commented on GitHub (Sep 18, 2025): <!-- Greeting --> Hi @firatciftci! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> This regression is caused by stricter type checks in the `serializeID` function of the `mongodbAdapter` starting in Better Auth v1.3.10. Now, any value passed as an ID (for fields like `id` or `_id`) must be a string or a MongoDB `ObjectId`—other types (like `null`, numbers, or unexpected objects) will trigger the `Invalid id value` error during login and user lookup operations. This change was introduced to enforce consistency and prevent silent failures in ID handling, but it can break setups where IDs are not always strings or ObjectIds, or where custom models have mismatched or missing `id` fields [[source](https://github.com/better-auth/better-auth/blob/d1fe10962079c82920ea078a9847f65a59907b81/packages/better-auth/src/adapters/mongodb-adapter/mongodb-adapter.ts)]. **Workaround:** You can disable Better Auth's internal ID generation by setting `advanced.database.generateId: false` in your auth config. This lets MongoDB generate ObjectIds automatically and prevents the adapter from trying to convert or validate IDs that aren't strings or ObjectIds [[source](https://github.com/better-auth/better-auth/issues/289)]. Example: ```js export const auth = betterAuth({ database: mongodbAdapter(client, { generateId: false }), plugins: [username(), sveltekitCookies(getRequestEvent)], emailAndPassword: { enabled: true }, }); ``` Make sure your MongoDB documents have valid `_id` fields and avoid having `id: null` or mismatched `id`/`_id` values. **Caveat:** If your setup uses custom models or schemas, double-check that all user/account/session documents have proper `_id` fields and that queries do not pass unexpected types for IDs. If you use Mongoose, ensure you have the `mongodb` package installed, as the adapter expects `ObjectId` from `mongodb` rather than Mongoose's type [[source](https://github.com/better-auth/better-auth/issues/1492)]. If you need more granular control, you can provide a custom ID generator via `advanced.database.generateId`—the adapter will then skip its own conversion and use your logic directly. Let me know if you need help with a specific model or query! <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/cb4997ea-0368-4c11-bd92-d0455a0137fc?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/cb4997ea-0368-4c11-bd92-d0455a0137fc?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/cb4997ea-0368-4c11-bd92-d0455a0137fc?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/cb4997ea-0368-4c11-bd92-d0455a0137fc?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/cb4997ea-0368-4c11-bd92-d0455a0137fc?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/cb4997ea-0368-4c11-bd92-d0455a0137fc?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/cb4997ea-0368-4c11-bd92-d0455a0137fc?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/4741)
Author
Owner

@himself65 commented on GitHub (Sep 18, 2025):

Could you please try 1.3.12?

@himself65 commented on GitHub (Sep 18, 2025): Could you please try 1.3.12?
Author
Owner

@firatciftci commented on GitHub (Sep 18, 2025):

@himself65 Just updated and still experiencing the same error as above during login.

@firatciftci commented on GitHub (Sep 18, 2025): @himself65 Just updated and still experiencing the same error as above during login.
Author
Owner

@himself65 commented on GitHub (Sep 18, 2025):

I set up locally and didn't see errors. Could you please provide more information? Like can you set a debugger there and provide the context varibales?

@himself65 commented on GitHub (Sep 18, 2025): I set up locally and didn't see errors. Could you please provide more information? Like can you set a debugger there and provide the context varibales?
Author
Owner

@firatciftci commented on GitHub (Sep 18, 2025):

Interestingly, the issue does not occur locally with the development server, only with a production build; running pnpm run preview on the local device for the Vite build alongside my Docker container for the actual production environment both experience the issue.

I also have a Next.js application with the identical Better Auth setup (version 1.3.12), and the issue does not occur there at all (development or production).

Perhaps there is something weird going on with SvelteKit's serialization that is interfering with Better Auth's functionality in a production build?

Hope these help a bit better to identify the issue; I will try to use a debugger and hope to share more technical data as well.

@firatciftci commented on GitHub (Sep 18, 2025): Interestingly, the issue does not occur locally with the development server, only with a production build; running `pnpm run preview` on the local device for the Vite build alongside my Docker container for the actual production environment both experience the issue. I also have a Next.js application with the identical Better Auth setup (version 1.3.12), and the issue does not occur there at all (development or production). Perhaps there is something weird going on with SvelteKit's serialization that is interfering with Better Auth's functionality in a production build? Hope these help a bit better to identify the issue; I will try to use a debugger and hope to share more technical data as well.
Author
Owner

@firatciftci commented on GitHub (Sep 18, 2025):

Same issue with a Vercel deployment using the Vercel adapter as well, so the issue should not be limited to the production environment type.

@firatciftci commented on GitHub (Sep 18, 2025): Same issue with a Vercel deployment using the Vercel adapter as well, so the issue should not be limited to the production environment type.
Author
Owner

@himself65 commented on GitHub (Sep 18, 2025):

The issue is from

f11d365e79/packages/better-auth/src/db/internal-adapter.ts (L717-L743)

I think it doesn't relate to the Svelte plugin since it does nothing.

@himself65 commented on GitHub (Sep 18, 2025): The issue is from https://github.com/better-auth/better-auth/blob/f11d365e7965f19cbfa7a533c822af8c1e9b3f14/packages/better-auth/src/db/internal-adapter.ts#L717-L743 I think it doesn't relate to the Svelte plugin since it does nothing.
Author
Owner

@himself65 commented on GitHub (Sep 18, 2025):

Anyway, if you can provide the reproduced code, I'm willing to help. Right now, I cannot reproduce locally.

@himself65 commented on GitHub (Sep 18, 2025): Anyway, if you can provide the reproduced code, I'm willing to help. Right now, I cannot reproduce locally.
Author
Owner

@himself65 commented on GitHub (Sep 18, 2025):

Index: pnpm-lock.yaml
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
--- a/pnpm-lock.yaml	(revision bc3253b00a9335f79ca0b73cbda700c9fec6cfe5)
+++ b/pnpm-lock.yaml	(date 1758217703699)
@@ -168,7 +168,7 @@
         version: 0.5.1(react-dom@19.1.1(react@19.1.1))(react@19.1.1)
       '@react-three/fiber':
         specifier: ^8.18.0
-        version: 8.18.0(de6zoezpf3ukbgngf33jdfxfpq)
+        version: 8.18.0(1a7d56a84bc02e5ad1bde2480f0aeeca)
       '@tanstack/react-query':
         specifier: ^5.85.9
         version: 5.85.9(react@19.1.1)
@@ -563,6 +563,16 @@
         specifier: ^1.55.0
         version: 1.55.0
 
+  e2e/integration/mongodb:
+    dependencies:
+      mongoose:
+        specifier: ^8.18.1
+        version: 8.18.1
+    devDependencies:
+      mongodb:
+        specifier: ^6.20.0
+        version: 6.20.0
+
   e2e/integration/solid-vinxi:
     dependencies:
       '@solidjs/router':
@@ -570,7 +580,7 @@
         version: 0.15.3(solid-js@1.9.9)
       '@solidjs/start':
         specifier: ^1.1.7
-        version: 1.1.7(ccvduuxloi3j37iwckcwkycibi)
+        version: 1.1.7(7c37fd26a8096bc07b4eef39619c825a)
       better-auth:
         specifier: workspace:*
         version: link:../../../packages/better-auth
@@ -2968,6 +2978,9 @@
   '@mongodb-js/saslprep@1.2.2':
     resolution: {integrity: sha512-EB0O3SCSNRUFk66iRCpI+cXzIjdswfCs7F6nOC3RAGJ7xr5YhaicvsRwJ9eyzYvYRlCSDUO/c7g4yNulxKC1WA==}
 
+  '@mongodb-js/saslprep@1.3.0':
+    resolution: {integrity: sha512-zlayKCsIjYb7/IdfqxorK5+xUMyi4vOKcFy10wKJYc63NSdKI8mNME+uJqfatkPmOSMMUiojrL58IePKBm3gvQ==}
+
   '@mrleebo/prisma-ast@0.13.0':
     resolution: {integrity: sha512-VxS+okLpNp6YUDLz3rAXv6sE8G4W5cX039bumkPub65xRr9BFxjHaT5ebX4DsiixIGaBwitjWTvx3mAbyI2EUQ==}
     engines: {node: '>=16'}
@@ -8404,6 +8417,10 @@
     resolution: {integrity: sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==}
     engines: {node: '>=18'}
 
+  kareem@2.6.3:
+    resolution: {integrity: sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==}
+    engines: {node: '>=12.0.0'}
+
   kind-of@6.0.3:
     resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==}
     engines: {node: '>=0.10.0'}
@@ -9277,6 +9294,37 @@
       socks:
         optional: true
 
+  mongodb@6.20.0:
+    resolution: {integrity: sha512-Tl6MEIU3K4Rq3TSHd+sZQqRBoGlFsOgNrH5ltAcFBV62Re3Fd+FcaVf8uSEQFOJ51SDowDVttBTONMfoYWrWlQ==}
+    engines: {node: '>=16.20.1'}
+    peerDependencies:
+      '@aws-sdk/credential-providers': ^3.188.0
+      '@mongodb-js/zstd': ^1.1.0 || ^2.0.0
+      gcp-metadata: ^5.2.0
+      kerberos: ^2.0.1
+      mongodb-client-encryption: '>=6.0.0 <7'
+      snappy: ^7.3.2
+      socks: ^2.7.1
+    peerDependenciesMeta:
+      '@aws-sdk/credential-providers':
+        optional: true
+      '@mongodb-js/zstd':
+        optional: true
+      gcp-metadata:
+        optional: true
+      kerberos:
+        optional: true
+      mongodb-client-encryption:
+        optional: true
+      snappy:
+        optional: true
+      socks:
+        optional: true
+
+  mongoose@8.18.1:
+    resolution: {integrity: sha512-K0RfrUXXufqNRZZjvAGdyjydB91SnbWxlwFYi5t7zN2DxVWFD3c6puia0/7xfBwZm6RCpYOVdYFlRFpoDWiC+w==}
+    engines: {node: '>=16.20.1'}
+
   motion-dom@12.23.12:
     resolution: {integrity: sha512-RcR4fvMCTESQBD/uKQe49D5RUeDOokkGRmz4ceaJKDBgHYtZtntC/s2vLvY38gqGaytinij/yi3hMcWVcEF5Kw==}
 
@@ -9297,6 +9345,14 @@
       react-dom:
         optional: true
 
+  mpath@0.9.0:
+    resolution: {integrity: sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==}
+    engines: {node: '>=4.0.0'}
+
+  mquery@5.0.0:
+    resolution: {integrity: sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==}
+    engines: {node: '>=14.0.0'}
+
   mri@1.2.0:
     resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==}
     engines: {node: '>=4'}
@@ -10834,6 +10890,9 @@
     resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==}
     engines: {node: '>= 0.4'}
 
+  sift@17.1.3:
+    resolution: {integrity: sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==}
+
   siginfo@2.0.0:
     resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
 
@@ -14312,6 +14371,10 @@
     dependencies:
       sparse-bitfield: 3.0.3
 
+  '@mongodb-js/saslprep@1.3.0':
+    dependencies:
+      sparse-bitfield: 3.0.3
+
   '@mrleebo/prisma-ast@0.13.0':
     dependencies:
       chevrotain: 10.5.0
@@ -15953,7 +16016,7 @@
     optionalDependencies:
       '@types/react': 19.1.12
 
-  '@react-three/fiber@8.18.0(de6zoezpf3ukbgngf33jdfxfpq)':
+  '@react-three/fiber@8.18.0(1a7d56a84bc02e5ad1bde2480f0aeeca)':
     dependencies:
       '@babel/runtime': 7.28.3
       '@types/react-reconciler': 0.26.7
@@ -16406,7 +16469,7 @@
     dependencies:
       solid-js: 1.9.9
 
-  '@solidjs/start@1.1.7(ccvduuxloi3j37iwckcwkycibi)':
+  '@solidjs/start@1.1.7(7c37fd26a8096bc07b4eef39619c825a)':
     dependencies:
       '@tanstack/server-functions-plugin': 1.121.21(vite@7.1.5(@types/node@24.4.0)(jiti@2.5.1)(less@4.4.1)(lightningcss@1.30.1)(sass@1.90.0)(terser@5.44.0)(tsx@4.20.5)(yaml@2.8.1))
       '@vinxi/plugin-directives': 0.5.1(vinxi@0.5.8(@azure/identity@4.11.1)(@libsql/client@0.15.14)(@netlify/blobs@10.0.8)(@types/node@24.4.0)(better-sqlite3@12.2.0)(db0@0.3.2(@libsql/client@0.15.14)(better-sqlite3@12.2.0)(drizzle-orm@0.44.5(@cloudflare/workers-types@4.20250903.0)(@libsql/client@0.15.14)(@prisma/client@5.22.0(prisma@5.22.0))(@types/better-sqlite3@7.6.13)(@types/pg@8.15.5)(better-sqlite3@12.2.0)(bun-types@1.2.21(@types/react@19.1.12))(kysely@0.28.5)(mysql2@3.14.4)(pg@8.16.3)(prisma@5.22.0))(mysql2@3.14.4))(drizzle-orm@0.44.5(@cloudflare/workers-types@4.20250903.0)(@libsql/client@0.15.14)(@prisma/client@5.22.0(prisma@5.22.0))(@types/better-sqlite3@7.6.13)(@types/pg@8.15.5)(better-sqlite3@12.2.0)(bun-types@1.2.21(@types/react@19.1.12))(kysely@0.28.5)(mysql2@3.14.4)(pg@8.16.3)(prisma@5.22.0))(ioredis@5.7.0)(jiti@2.5.1)(less@4.4.1)(lightningcss@1.30.1)(mysql2@3.14.4)(sass@1.90.0)(terser@5.44.0)(tsx@4.20.5)(yaml@2.8.1))
@@ -20564,6 +20627,8 @@
 
   jwt-decode@4.0.0: {}
 
+  kareem@2.6.3: {}
+
   kind-of@6.0.3: {}
 
   kleur@3.0.3: {}
@@ -21874,6 +21939,31 @@
       bson: 6.10.4
       mongodb-connection-string-url: 3.0.2
 
+  mongodb@6.20.0:
+    dependencies:
+      '@mongodb-js/saslprep': 1.3.0
+      bson: 6.10.4
+      mongodb-connection-string-url: 3.0.2
+
+  mongoose@8.18.1:
+    dependencies:
+      bson: 6.10.4
+      kareem: 2.6.3
+      mongodb: 6.18.0
+      mpath: 0.9.0
+      mquery: 5.0.0
+      ms: 2.1.3
+      sift: 17.1.3
+    transitivePeerDependencies:
+      - '@aws-sdk/credential-providers'
+      - '@mongodb-js/zstd'
+      - gcp-metadata
+      - kerberos
+      - mongodb-client-encryption
+      - snappy
+      - socks
+      - supports-color
+
   motion-dom@12.23.12:
     dependencies:
       motion-utils: 12.23.6
@@ -21888,6 +21978,14 @@
       react: 19.1.1
       react-dom: 19.1.1(react@19.1.1)
 
+  mpath@0.9.0: {}
+
+  mquery@5.0.0:
+    dependencies:
+      debug: 4.4.1
+    transitivePeerDependencies:
+      - supports-color
+
   mri@1.2.0: {}
 
   mrmime@2.0.1: {}
@@ -23942,6 +24040,8 @@
       side-channel-map: 1.0.1
       side-channel-weakmap: 1.0.2
 
+  sift@17.1.3: {}
+
   siginfo@2.0.0: {}
 
   signal-exit@3.0.7: {}
Index: e2e/integration/mongodb/package.json
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/e2e/integration/mongodb/package.json b/e2e/integration/mongodb/package.json
new file mode 100644
--- /dev/null	(date 1758217703697)
+++ b/e2e/integration/mongodb/package.json	(date 1758217703697)
@@ -0,0 +1,13 @@
+{
+  "name": "mongodb",
+  "type": "module",
+  "scripts": {
+    "start": "tsx ./src/auth.ts"
+  },
+  "devDependencies": {
+    "mongodb": "^6.20.0"
+  },
+  "dependencies": {
+    "mongoose": "^8.18.1"
+  }
+}
Index: e2e/integration/mongodb/tsconfig.json
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/e2e/integration/mongodb/tsconfig.json b/e2e/integration/mongodb/tsconfig.json
new file mode 100644
--- /dev/null	(date 1758217703697)
+++ b/e2e/integration/mongodb/tsconfig.json	(date 1758217703697)
@@ -0,0 +1,21 @@
+{
+  "compilerOptions": {
+    "target": "ES2022",
+    "useDefineForClassFields": true,
+    "module": "ESNext",
+    "lib": ["ES2022"],
+    "skipLibCheck": true,
+    "moduleResolution": "bundler",
+    "allowImportingTsExtensions": true,
+    "verbatimModuleSyntax": true,
+    "moduleDetection": "force",
+    "noEmit": true,
+    "strict": true,
+    "noUnusedLocals": true,
+    "noUnusedParameters": true,
+    "erasableSyntaxOnly": true,
+    "noFallthroughCasesInSwitch": true,
+    "noUncheckedSideEffectImports": true
+  },
+  "include": ["src"]
+}
Index: e2e/integration/mongodb/src/auth.ts
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/e2e/integration/mongodb/src/auth.ts b/e2e/integration/mongodb/src/auth.ts
new file mode 100644
--- /dev/null	(date 1758217703697)
+++ b/e2e/integration/mongodb/src/auth.ts	(date 1758217703697)
@@ -0,0 +1,37 @@
+import { betterAuth } from 'better-auth'
+import { mongodbAdapter } from 'better-auth/adapters/mongodb'
+import mongoose from 'mongoose'
+
+await mongoose.connect(
+  'mongodb+srv://himself65:GG3WblNHuSvZwzCo@cluster0.piavqal.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0')
+
+const client = mongoose.connection.db!
+
+export const auth = betterAuth({
+  database: mongodbAdapter(client),
+  logger: {
+    level: 'debug'
+  },
+  emailAndPassword: {
+    enabled: true
+  }
+})
+
+// auth.api.signUpEmail({
+//   body: {
+//     name: 'alex',
+//     email: 'himself65@outlook.com',
+//     password: 'hello12345'
+//   }
+// }).then(r => {
+//   console.log(r)
+// })
+
+auth.api.signInEmail({
+  body: {
+    email: 'himself65@outlook.com',
+    password: 'hello12345'
+  }
+}).then(r => {
+  console.log(r)
+})
\ No newline at end of file

api key has been revoked

@himself65 commented on GitHub (Sep 18, 2025): ```patch Index: pnpm-lock.yaml IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml --- a/pnpm-lock.yaml (revision bc3253b00a9335f79ca0b73cbda700c9fec6cfe5) +++ b/pnpm-lock.yaml (date 1758217703699) @@ -168,7 +168,7 @@ version: 0.5.1(react-dom@19.1.1(react@19.1.1))(react@19.1.1) '@react-three/fiber': specifier: ^8.18.0 - version: 8.18.0(de6zoezpf3ukbgngf33jdfxfpq) + version: 8.18.0(1a7d56a84bc02e5ad1bde2480f0aeeca) '@tanstack/react-query': specifier: ^5.85.9 version: 5.85.9(react@19.1.1) @@ -563,6 +563,16 @@ specifier: ^1.55.0 version: 1.55.0 + e2e/integration/mongodb: + dependencies: + mongoose: + specifier: ^8.18.1 + version: 8.18.1 + devDependencies: + mongodb: + specifier: ^6.20.0 + version: 6.20.0 + e2e/integration/solid-vinxi: dependencies: '@solidjs/router': @@ -570,7 +580,7 @@ version: 0.15.3(solid-js@1.9.9) '@solidjs/start': specifier: ^1.1.7 - version: 1.1.7(ccvduuxloi3j37iwckcwkycibi) + version: 1.1.7(7c37fd26a8096bc07b4eef39619c825a) better-auth: specifier: workspace:* version: link:../../../packages/better-auth @@ -2968,6 +2978,9 @@ '@mongodb-js/saslprep@1.2.2': resolution: {integrity: sha512-EB0O3SCSNRUFk66iRCpI+cXzIjdswfCs7F6nOC3RAGJ7xr5YhaicvsRwJ9eyzYvYRlCSDUO/c7g4yNulxKC1WA==} + '@mongodb-js/saslprep@1.3.0': + resolution: {integrity: sha512-zlayKCsIjYb7/IdfqxorK5+xUMyi4vOKcFy10wKJYc63NSdKI8mNME+uJqfatkPmOSMMUiojrL58IePKBm3gvQ==} + '@mrleebo/prisma-ast@0.13.0': resolution: {integrity: sha512-VxS+okLpNp6YUDLz3rAXv6sE8G4W5cX039bumkPub65xRr9BFxjHaT5ebX4DsiixIGaBwitjWTvx3mAbyI2EUQ==} engines: {node: '>=16'} @@ -8404,6 +8417,10 @@ resolution: {integrity: sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==} engines: {node: '>=18'} + kareem@2.6.3: + resolution: {integrity: sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==} + engines: {node: '>=12.0.0'} + kind-of@6.0.3: resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==} engines: {node: '>=0.10.0'} @@ -9277,6 +9294,37 @@ socks: optional: true + mongodb@6.20.0: + resolution: {integrity: sha512-Tl6MEIU3K4Rq3TSHd+sZQqRBoGlFsOgNrH5ltAcFBV62Re3Fd+FcaVf8uSEQFOJ51SDowDVttBTONMfoYWrWlQ==} + engines: {node: '>=16.20.1'} + peerDependencies: + '@aws-sdk/credential-providers': ^3.188.0 + '@mongodb-js/zstd': ^1.1.0 || ^2.0.0 + gcp-metadata: ^5.2.0 + kerberos: ^2.0.1 + mongodb-client-encryption: '>=6.0.0 <7' + snappy: ^7.3.2 + socks: ^2.7.1 + peerDependenciesMeta: + '@aws-sdk/credential-providers': + optional: true + '@mongodb-js/zstd': + optional: true + gcp-metadata: + optional: true + kerberos: + optional: true + mongodb-client-encryption: + optional: true + snappy: + optional: true + socks: + optional: true + + mongoose@8.18.1: + resolution: {integrity: sha512-K0RfrUXXufqNRZZjvAGdyjydB91SnbWxlwFYi5t7zN2DxVWFD3c6puia0/7xfBwZm6RCpYOVdYFlRFpoDWiC+w==} + engines: {node: '>=16.20.1'} + motion-dom@12.23.12: resolution: {integrity: sha512-RcR4fvMCTESQBD/uKQe49D5RUeDOokkGRmz4ceaJKDBgHYtZtntC/s2vLvY38gqGaytinij/yi3hMcWVcEF5Kw==} @@ -9297,6 +9345,14 @@ react-dom: optional: true + mpath@0.9.0: + resolution: {integrity: sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==} + engines: {node: '>=4.0.0'} + + mquery@5.0.0: + resolution: {integrity: sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==} + engines: {node: '>=14.0.0'} + mri@1.2.0: resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==} engines: {node: '>=4'} @@ -10834,6 +10890,9 @@ resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==} engines: {node: '>= 0.4'} + sift@17.1.3: + resolution: {integrity: sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==} + siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} @@ -14312,6 +14371,10 @@ dependencies: sparse-bitfield: 3.0.3 + '@mongodb-js/saslprep@1.3.0': + dependencies: + sparse-bitfield: 3.0.3 + '@mrleebo/prisma-ast@0.13.0': dependencies: chevrotain: 10.5.0 @@ -15953,7 +16016,7 @@ optionalDependencies: '@types/react': 19.1.12 - '@react-three/fiber@8.18.0(de6zoezpf3ukbgngf33jdfxfpq)': + '@react-three/fiber@8.18.0(1a7d56a84bc02e5ad1bde2480f0aeeca)': dependencies: '@babel/runtime': 7.28.3 '@types/react-reconciler': 0.26.7 @@ -16406,7 +16469,7 @@ dependencies: solid-js: 1.9.9 - '@solidjs/start@1.1.7(ccvduuxloi3j37iwckcwkycibi)': + '@solidjs/start@1.1.7(7c37fd26a8096bc07b4eef39619c825a)': dependencies: '@tanstack/server-functions-plugin': 1.121.21(vite@7.1.5(@types/node@24.4.0)(jiti@2.5.1)(less@4.4.1)(lightningcss@1.30.1)(sass@1.90.0)(terser@5.44.0)(tsx@4.20.5)(yaml@2.8.1)) '@vinxi/plugin-directives': 0.5.1(vinxi@0.5.8(@azure/identity@4.11.1)(@libsql/client@0.15.14)(@netlify/blobs@10.0.8)(@types/node@24.4.0)(better-sqlite3@12.2.0)(db0@0.3.2(@libsql/client@0.15.14)(better-sqlite3@12.2.0)(drizzle-orm@0.44.5(@cloudflare/workers-types@4.20250903.0)(@libsql/client@0.15.14)(@prisma/client@5.22.0(prisma@5.22.0))(@types/better-sqlite3@7.6.13)(@types/pg@8.15.5)(better-sqlite3@12.2.0)(bun-types@1.2.21(@types/react@19.1.12))(kysely@0.28.5)(mysql2@3.14.4)(pg@8.16.3)(prisma@5.22.0))(mysql2@3.14.4))(drizzle-orm@0.44.5(@cloudflare/workers-types@4.20250903.0)(@libsql/client@0.15.14)(@prisma/client@5.22.0(prisma@5.22.0))(@types/better-sqlite3@7.6.13)(@types/pg@8.15.5)(better-sqlite3@12.2.0)(bun-types@1.2.21(@types/react@19.1.12))(kysely@0.28.5)(mysql2@3.14.4)(pg@8.16.3)(prisma@5.22.0))(ioredis@5.7.0)(jiti@2.5.1)(less@4.4.1)(lightningcss@1.30.1)(mysql2@3.14.4)(sass@1.90.0)(terser@5.44.0)(tsx@4.20.5)(yaml@2.8.1)) @@ -20564,6 +20627,8 @@ jwt-decode@4.0.0: {} + kareem@2.6.3: {} + kind-of@6.0.3: {} kleur@3.0.3: {} @@ -21874,6 +21939,31 @@ bson: 6.10.4 mongodb-connection-string-url: 3.0.2 + mongodb@6.20.0: + dependencies: + '@mongodb-js/saslprep': 1.3.0 + bson: 6.10.4 + mongodb-connection-string-url: 3.0.2 + + mongoose@8.18.1: + dependencies: + bson: 6.10.4 + kareem: 2.6.3 + mongodb: 6.18.0 + mpath: 0.9.0 + mquery: 5.0.0 + ms: 2.1.3 + sift: 17.1.3 + transitivePeerDependencies: + - '@aws-sdk/credential-providers' + - '@mongodb-js/zstd' + - gcp-metadata + - kerberos + - mongodb-client-encryption + - snappy + - socks + - supports-color + motion-dom@12.23.12: dependencies: motion-utils: 12.23.6 @@ -21888,6 +21978,14 @@ react: 19.1.1 react-dom: 19.1.1(react@19.1.1) + mpath@0.9.0: {} + + mquery@5.0.0: + dependencies: + debug: 4.4.1 + transitivePeerDependencies: + - supports-color + mri@1.2.0: {} mrmime@2.0.1: {} @@ -23942,6 +24040,8 @@ side-channel-map: 1.0.1 side-channel-weakmap: 1.0.2 + sift@17.1.3: {} + siginfo@2.0.0: {} signal-exit@3.0.7: {} Index: e2e/integration/mongodb/package.json IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== diff --git a/e2e/integration/mongodb/package.json b/e2e/integration/mongodb/package.json new file mode 100644 --- /dev/null (date 1758217703697) +++ b/e2e/integration/mongodb/package.json (date 1758217703697) @@ -0,0 +1,13 @@ +{ + "name": "mongodb", + "type": "module", + "scripts": { + "start": "tsx ./src/auth.ts" + }, + "devDependencies": { + "mongodb": "^6.20.0" + }, + "dependencies": { + "mongoose": "^8.18.1" + } +} Index: e2e/integration/mongodb/tsconfig.json IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== diff --git a/e2e/integration/mongodb/tsconfig.json b/e2e/integration/mongodb/tsconfig.json new file mode 100644 --- /dev/null (date 1758217703697) +++ b/e2e/integration/mongodb/tsconfig.json (date 1758217703697) @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "useDefineForClassFields": true, + "module": "ESNext", + "lib": ["ES2022"], + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["src"] +} Index: e2e/integration/mongodb/src/auth.ts IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== diff --git a/e2e/integration/mongodb/src/auth.ts b/e2e/integration/mongodb/src/auth.ts new file mode 100644 --- /dev/null (date 1758217703697) +++ b/e2e/integration/mongodb/src/auth.ts (date 1758217703697) @@ -0,0 +1,37 @@ +import { betterAuth } from 'better-auth' +import { mongodbAdapter } from 'better-auth/adapters/mongodb' +import mongoose from 'mongoose' + +await mongoose.connect( + 'mongodb+srv://himself65:GG3WblNHuSvZwzCo@cluster0.piavqal.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0') + +const client = mongoose.connection.db! + +export const auth = betterAuth({ + database: mongodbAdapter(client), + logger: { + level: 'debug' + }, + emailAndPassword: { + enabled: true + } +}) + +// auth.api.signUpEmail({ +// body: { +// name: 'alex', +// email: 'himself65@outlook.com', +// password: 'hello12345' +// } +// }).then(r => { +// console.log(r) +// }) + +auth.api.signInEmail({ + body: { + email: 'himself65@outlook.com', + password: 'hello12345' + } +}).then(r => { + console.log(r) +}) \ No newline at end of file ``` > api key has been revoked
Author
Owner

@himself65 commented on GitHub (Sep 18, 2025):

Oh, I see this failure in our CI

https://github.com/better-auth/better-auth/actions/runs/17839287445/job/50724318430?pr=4740

@himself65 commented on GitHub (Sep 18, 2025): Oh, I see this failure in our CI https://github.com/better-auth/better-auth/actions/runs/17839287445/job/50724318430?pr=4740
Author
Owner

@himself65 commented on GitHub (Sep 18, 2025):

Hi, could you please provide the final db table schema?

@himself65 commented on GitHub (Sep 18, 2025): Hi, could you please provide the final db table schema?
Author
Owner

@firatciftci commented on GitHub (Sep 18, 2025):

Hi again, I have created a simple SvelteKit application with a brand new MongoDB database (using Mongoose on the frontend) and the bare minimum Better Auth setup. You can find it here: https://github.com/firatciftci/better-auth-sveltekit-reproduction. You only need MONGODB_URL, BETTER_AUTH_SECRET, and BETTER_AUTH_URL as environment variables.

My brand new MongoDB database tied to this application has three collections: users, accounts, and sessions.

users:

_id: ObjectId
name: string
email: string
emailVerified: boolean
createdAt: Date
updatedAt: Date

accounts:

_id: ObjectId
accountId: string
providerId: string
userId: ObjectId
password: string
createdAt: Date
updatedAt: Date

sessions:

_id: ObjectId
expiresAt: Date
token: string
createdAt: Date
updatedAt: Date
ipAddress: string
userAgent: string
userId: ObjectId
@firatciftci commented on GitHub (Sep 18, 2025): Hi again, I have created a simple SvelteKit application with a brand new MongoDB database (using Mongoose on the frontend) and the bare minimum Better Auth setup. You can find it here: https://github.com/firatciftci/better-auth-sveltekit-reproduction. You only need `MONGODB_URL`, `BETTER_AUTH_SECRET`, and `BETTER_AUTH_URL` as environment variables. My brand new MongoDB database tied to this application has three collections: `users`, `accounts`, and `sessions`. `users`: ``` _id: ObjectId name: string email: string emailVerified: boolean createdAt: Date updatedAt: Date ``` `accounts`: ``` _id: ObjectId accountId: string providerId: string userId: ObjectId password: string createdAt: Date updatedAt: Date ``` `sessions`: ``` _id: ObjectId expiresAt: Date token: string createdAt: Date updatedAt: Date ipAddress: string userAgent: string userId: ObjectId ```
Author
Owner

@firatciftci commented on GitHub (Sep 18, 2025):

The same error occurs in this one too; please build the application using pnpm run build and then run the production server locally using pnpm run preview. Then, sign up (which should work), and then try to log in (which should error).

@firatciftci commented on GitHub (Sep 18, 2025): The same error occurs in this one too; please build the application using `pnpm run build` and then run the production server locally using `pnpm run preview`. Then, sign up (which should work), and then try to log in (which should error).
Author
Owner

@firatciftci commented on GitHub (Sep 18, 2025):

One important breakthrough: No errors occur with the mongodb package instead of mongoose; so my guess is that the serialization for the ID is experiencing a type mismatch between the official MongoDB driver and Mongoose's wrapper around it, given the error.

Please see the "mongodb" branch in the repository linked above for the working version.

@firatciftci commented on GitHub (Sep 18, 2025): One important breakthrough: No errors occur with the `mongodb` package instead of `mongoose`; so my guess is that the serialization for the ID is experiencing a type mismatch between the official MongoDB driver and Mongoose's wrapper around it, given the error. Please see the "mongodb" branch in the repository linked above for the working version.
Author
Owner

@himself65 commented on GitHub (Sep 18, 2025):

One important breakthrough: No errors occur with the mongodb package instead of mongoose; so my guess is that the serialization for the ID is experiencing a type mismatch between the official MongoDB driver and Mongoose's wrapper around it, given the error.

Please see the "mongodb" branch in the repository linked above for the working version.

This is a good finding, yeah, we don't actually test Mongoose yet.

@himself65 commented on GitHub (Sep 18, 2025): > One important breakthrough: No errors occur with the `mongodb` package instead of `mongoose`; so my guess is that the serialization for the ID is experiencing a type mismatch between the official MongoDB driver and Mongoose's wrapper around it, given the error. > > Please see the "mongodb" branch in the repository linked above for the working version. This is a good finding, yeah, we don't actually test Mongoose yet.
Author
Owner

@firatciftci commented on GitHub (Sep 18, 2025):

Could it be not related to transactions, but actually this change: https://github.com/better-auth/better-auth/pull/3178

Given transactions are off by default with the most recent version, I believe it must be related to something going on here.

Sorry, didn't realize this change is from a while back. I'm lost so I'll stop guessing the culprit!


Please let me know if there is anything (else) I can do to help out and/or fix this issue. Though I completely understand that Better Auth does not have Mongoose as a first-class library akin to the MongoDB driver one for this use case, given how much of MongoDB-based applications use Mongoose to interface with the database, I believe this is highly critical.

@firatciftci commented on GitHub (Sep 18, 2025): ~Could it be not related to transactions, but actually this change: https://github.com/better-auth/better-auth/pull/3178~ ~Given transactions are off by default with the most recent version, I believe it must be related to something going on here.~ _Sorry, didn't realize this change is from a while back. I'm lost so I'll stop guessing the culprit!_ --- Please let me know if there is anything (else) I can do to help out and/or fix this issue. Though I completely understand that Better Auth does not have Mongoose as a first-class library akin to the MongoDB driver one for this use case, given how much of MongoDB-based applications use Mongoose to interface with the database, I believe this is highly critical.
Author
Owner

@firatciftci commented on GitHub (Sep 18, 2025):

I think it doesn't relate to the Svelte plugin since it does nothing.

I'm just more confused as to why my Next.js application with the same setup works, but not my SvelteKit one.

@firatciftci commented on GitHub (Sep 18, 2025): > I think it doesn't relate to the Svelte plugin since it does nothing. I'm just more confused as to why my Next.js application with the same setup works, but not my SvelteKit one.
Author
Owner

@himself65 commented on GitHub (Sep 18, 2025):

try to see if lock files are same

@himself65 commented on GitHub (Sep 18, 2025): try to see if lock files are same
Author
Owner

@firatciftci commented on GitHub (Sep 18, 2025):

Yes, both have up-to date lockfiles. Next.js has no issues, SvelteKit does.

That all said, adding this to my Better Auth config fixed the issue:

import { Types } from "mongoose";

...

advanced: {
  database: {
    generateId() {
      return new Types.ObjectId().toString();
    },
  },
},
@firatciftci commented on GitHub (Sep 18, 2025): Yes, both have up-to date lockfiles. Next.js has no issues, SvelteKit does. That all said, adding this to my Better Auth config fixed the issue: ```ts import { Types } from "mongoose"; ... advanced: { database: { generateId() { return new Types.ObjectId().toString(); }, }, }, ```
Author
Owner

@himself65 commented on GitHub (Sep 18, 2025):

Hi @ping-maxwell, can you take a look? This is seems like a small intergration issue

@himself65 commented on GitHub (Sep 18, 2025): Hi @ping-maxwell, can you take a look? This is seems like a small intergration issue
Author
Owner

@ping-maxwell commented on GitHub (Sep 19, 2025):

Yes, both have up-to date lockfiles. Next.js has no issues, SvelteKit does.

That all said, adding this to my Better Auth config fixed the issue:

import { Types } from "mongoose";

...

advanced: {
database: {
generateId() {
return new Types.ObjectId().toString();
},
},
},

@firatciftci
So with this, are you using mongoose? or just mongodb? - just want to confirm

@ping-maxwell commented on GitHub (Sep 19, 2025): > Yes, both have up-to date lockfiles. Next.js has no issues, SvelteKit does. > > That all said, adding this to my Better Auth config fixed the issue: > > import { Types } from "mongoose"; > > ... > > advanced: { > database: { > generateId() { > return new Types.ObjectId().toString(); > }, > }, > }, @firatciftci So with this, are you using mongoose? or just mongodb? - just want to confirm
Author
Owner

@himself65 commented on GitHub (Sep 19, 2025):

We don't support mongoose built-in. So I think we won't gonna fix this. But feel free to impement mongoose adapter

@himself65 commented on GitHub (Sep 19, 2025): We don't support `mongoose` built-in. So I think we won't gonna fix this. But feel free to impement mongoose adapter
Author
Owner

@aymericzip commented on GitHub (Nov 14, 2025):

I got the same issue (block login in prod only)

I upgraded mongo to the v7, downgrading it to v6.21.0 fixed it

@aymericzip commented on GitHub (Nov 14, 2025): I got the same issue (block login in prod only) I upgraded mongo to the v7, downgrading it to v6.21.0 fixed it
Author
Owner

@quanghuynt14 commented on GitHub (Dec 12, 2025):

I also got this issue with mongo native driver.

import { ObjectId } from "mongodb";

...

advanced: {
  database: {
    generateId() {
      return new ObjectId().toString();
    },
  },
},

I confirmed that adding this code fixed the bug but I think it's a quickwin. We should fix the root cause of this issue.

@quanghuynt14 commented on GitHub (Dec 12, 2025): I also got this issue with `mongo` native driver. ```ts import { ObjectId } from "mongodb"; ... advanced: { database: { generateId() { return new ObjectId().toString(); }, }, }, ``` I confirmed that adding this code fixed the bug but I think it's a quickwin. We should fix the root cause of this issue.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#1956