[GH-ISSUE #5454] MongoDB Adapter: List all sortable fields to index #10250

Open
opened 2026-04-13 06:14:48 -05:00 by GiteaMirror · 5 comments
Owner

Originally created by @FrancescoSaverioZuppichini on GitHub (Oct 21, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/5454

Originally assigned to: @ping-maxwell on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Hi there,

Thanks a lot for the amazing library. So, when I am using the mongodb adapter

export const auth = betterAuth({
  database: mongodbAdapter(db, { client }),
})

I am getting the following error

[error] MongoServerError [MongoServerError: Error=2, Details='Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: 6a145939-9eda-48df-90ca-0d2d6a2cb653; Reason: (Message: {"Errors":["The index path corresponding to the specified order-by item is excluded."]}
ActivityId: 6a145939-9eda-48df-90ca-0d2d6a2cb653, Request URI: /apps/7f174cbf-f9de-4e31-9db0-d63c3296a5ae/services/55753137-c7b8-4139-a5d6-6c75de362034/partitions/63636c21-fbac-467e-a0e4-39ee21c39c8d/replicas/134054376123480988s/, RequestStats: Microsoft.Azure.Cosmos.Tracing.TraceData.ClientSideRequestStatisticsTraceDatum, SDK: Windows/10.0.20348 cosmos-netstandard-sdk/3.18.0);] {
  errorResponse: [Object],
  ok: 0,
  code: 2,
  codeName: 'BadValue'
}

This means that one field that is being used for .sort is not indexed; this is required in cosmosDB for example. Do you have a list of fields that are used for sorting? I think one is .createdAt.

Thanks a lot

Current vs. Expected behavior

We should explain (with a code example) how to create such indexes in the doc (happy to contribute)

What version of Better Auth are you using?

^1.3.28

System info

{
  "system": {
    "platform": "darwin",
    "arch": "arm64",
    "version": "Darwin Kernel Version 24.6.0: Mon Aug 11 21:16:52 PDT 2025; root:xnu-11417.140.69.701.11~1/RELEASE_ARM64_T8112",
    "release": "24.6.0",
    "cpuCount": 8,
    "cpuModel": "Apple M2",
    "totalMemory": "16.00 GB",
    "freeMemory": "0.59 GB"
  },
  "node": {
    "version": "v22.13.0",
    "env": "development"
  },
  "packageManager": {
    "name": "bun",
    "version": "1.2.0"
  },
  "frameworks": [
    {
      "name": "next",
      "version": "15.5.4"
    },
    {
      "name": "react",
      "version": "19.1.1"
    }
  ],
  "databases": [
    {
      "name": "mongodb",
      "version": "^6.9.0"
    }
  ],
  "betterAuth": {
    "version": "^1.3.28",
    "config": {
      "socialProviders": {
        "microsoft": {
          "clientId": "[REDACTED]",
          "clientSecret": "[REDACTED]",
          "tenantId": "473672ba-cd07-4371-a2ae-788b4c61840e",
          "authority": "https://login.microsoftonline.com",
          "disableDefaultScope": true,
          "scope": [
            "openid",
            "profile",
            "email",
            "offline_access",
            "api://voiceiq-dev/user_impersonation"
          ],
          "prompt": "select_account"
        }
      },
      "logger": {
        "level": "debug"
      },
      "user": {
        "additionalFields": {
          "groups": {
            "type": "string[]",
            "input": false
          }
        }
      }
    }
  }
}

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

Backend

Auth config (if applicable)

import { betterAuth } from "better-auth"
export const auth = betterAuth({
  emailAndPassword: {  
    enabled: true
  },
});

Additional context

No response

Originally created by @FrancescoSaverioZuppichini on GitHub (Oct 21, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/5454 Originally assigned to: @ping-maxwell on GitHub. ### Is this suited for github? - [ ] Yes, this is suited for github ### To Reproduce Hi there, Thanks a lot for the amazing library. So, when I am using the mongodb adapter ```js export const auth = betterAuth({ database: mongodbAdapter(db, { client }), }) ``` I am getting the following error ``` [error] MongoServerError [MongoServerError: Error=2, Details='Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: 6a145939-9eda-48df-90ca-0d2d6a2cb653; Reason: (Message: {"Errors":["The index path corresponding to the specified order-by item is excluded."]} ActivityId: 6a145939-9eda-48df-90ca-0d2d6a2cb653, Request URI: /apps/7f174cbf-f9de-4e31-9db0-d63c3296a5ae/services/55753137-c7b8-4139-a5d6-6c75de362034/partitions/63636c21-fbac-467e-a0e4-39ee21c39c8d/replicas/134054376123480988s/, RequestStats: Microsoft.Azure.Cosmos.Tracing.TraceData.ClientSideRequestStatisticsTraceDatum, SDK: Windows/10.0.20348 cosmos-netstandard-sdk/3.18.0);] { errorResponse: [Object], ok: 0, code: 2, codeName: 'BadValue' } ``` This means that one field that is being used for .sort is not indexed; this is required in cosmosDB for example. Do you have a list of fields that are used for sorting? I think one is .createdAt. Thanks a lot ### Current vs. Expected behavior We should explain (with a code example) how to create such indexes in the doc (happy to contribute) ### What version of Better Auth are you using? ^1.3.28 ### System info ```bash { "system": { "platform": "darwin", "arch": "arm64", "version": "Darwin Kernel Version 24.6.0: Mon Aug 11 21:16:52 PDT 2025; root:xnu-11417.140.69.701.11~1/RELEASE_ARM64_T8112", "release": "24.6.0", "cpuCount": 8, "cpuModel": "Apple M2", "totalMemory": "16.00 GB", "freeMemory": "0.59 GB" }, "node": { "version": "v22.13.0", "env": "development" }, "packageManager": { "name": "bun", "version": "1.2.0" }, "frameworks": [ { "name": "next", "version": "15.5.4" }, { "name": "react", "version": "19.1.1" } ], "databases": [ { "name": "mongodb", "version": "^6.9.0" } ], "betterAuth": { "version": "^1.3.28", "config": { "socialProviders": { "microsoft": { "clientId": "[REDACTED]", "clientSecret": "[REDACTED]", "tenantId": "473672ba-cd07-4371-a2ae-788b4c61840e", "authority": "https://login.microsoftonline.com", "disableDefaultScope": true, "scope": [ "openid", "profile", "email", "offline_access", "api://voiceiq-dev/user_impersonation" ], "prompt": "select_account" } }, "logger": { "level": "debug" }, "user": { "additionalFields": { "groups": { "type": "string[]", "input": false } } } } } } ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth" export const auth = betterAuth({ emailAndPassword: { enabled: true }, }); ``` ### Additional context _No response_
GiteaMirror added the database label 2026-04-13 06:14:48 -05:00
Author
Owner

@FrancescoSaverioZuppichini commented on GitHub (Oct 21, 2025):

Adding index to createdAt worked:

const user = db.collection("user")
user.createIndex({ createdAt: -1 })

const account = db.collection("account")
account.createIndex({ createdAt: -1 })

const session = db.collection("session")
session.createIndex({ createdAt: -1 })

const verification = db.collection("verification")
verification.createIndex({ createdAt: -1 })

const rateLimit = db.collection("rate-limit")
rateLimit.createIndex({ createdAt: -1 })

const organization = db.collection("organization")
organization.createIndex({ createdAt: -1 })

const member = db.collection("member")
member.createIndex({ createdAt: -1 })

const invitation = db.collection("invitation")
invitation.createIndex({ createdAt: -1 })

const jwks = db.collection("jwks")
jwks.createIndex({ createdAt: -1 })

const passkey = db.collection("passkey")
passkey.createIndex({ createdAt: -1 })

const twoFactor = db.collection("two-factor")
twoFactor.createIndex({ createdAt: -1 })
<!-- gh-comment-id:3426527503 --> @FrancescoSaverioZuppichini commented on GitHub (Oct 21, 2025): Adding index to createdAt worked: ```js const user = db.collection("user") user.createIndex({ createdAt: -1 }) const account = db.collection("account") account.createIndex({ createdAt: -1 }) const session = db.collection("session") session.createIndex({ createdAt: -1 }) const verification = db.collection("verification") verification.createIndex({ createdAt: -1 }) const rateLimit = db.collection("rate-limit") rateLimit.createIndex({ createdAt: -1 }) const organization = db.collection("organization") organization.createIndex({ createdAt: -1 }) const member = db.collection("member") member.createIndex({ createdAt: -1 }) const invitation = db.collection("invitation") invitation.createIndex({ createdAt: -1 }) const jwks = db.collection("jwks") jwks.createIndex({ createdAt: -1 }) const passkey = db.collection("passkey") passkey.createIndex({ createdAt: -1 }) const twoFactor = db.collection("two-factor") twoFactor.createIndex({ createdAt: -1 }) ```
Author
Owner

@ping-maxwell commented on GitHub (Oct 22, 2025):

Do you have a list of fields that are used for sorting?

We don't really have a list as of now. The closest way for me to find all sortable fields are to look for all fields defined under the berrer-auth schema which has a field labeled sortable but I don't think this is properly used across all of BA 🤔

<!-- gh-comment-id:3432819689 --> @ping-maxwell commented on GitHub (Oct 22, 2025): > Do you have a list of fields that are used for sorting? We don't really have a list as of now. The closest way for me to find all sortable fields are to look for all fields defined under the berrer-auth schema which has a field labeled `sortable` but I don't think this is properly used across all of BA 🤔
Author
Owner

@ryami333 commented on GitHub (Dec 4, 2025):

Adding indices to createdAt like @FrancescoSaverioZuppichini suggested seemed to fix my issues with using the mongodbAdapter with Azure CosmosDB. Could this be upstreamed into the adaptor?

<!-- gh-comment-id:3611494448 --> @ryami333 commented on GitHub (Dec 4, 2025): Adding indices to `createdAt` like @FrancescoSaverioZuppichini suggested seemed to fix my issues with using the `mongodbAdapter` with Azure CosmosDB. Could this be upstreamed into the adaptor?
Author
Owner

@dosubot[bot] commented on GitHub (Mar 5, 2026):

Hi, @FrancescoSaverioZuppichini. I'm Dosu, and I'm helping the better-auth team manage their backlog and am marking this issue as stale.

Issue Summary

  • You reported sorting errors with the MongoDB adapter on unindexed fields in CosmosDB, which requires indexes for sorting.
  • You provided a detailed list of collections needing a createdAt index to fix this.
  • Contributors confirmed that adding createdAt indexes resolved the issue.
  • There is no official list of sortable fields, and the schema's "sortable" label is inconsistently applied.
  • A suggestion was made to integrate index management into the adapter and improve documentation for CosmosDB support.

Next Steps

  • Please let me know if this issue is still relevant with the latest version of better-auth by commenting here.
  • If I don’t hear back within 7 days, I will automatically close this issue.

Thanks for your understanding and contribution!

<!-- gh-comment-id:4006189647 --> @dosubot[bot] commented on GitHub (Mar 5, 2026): Hi, @FrancescoSaverioZuppichini. I'm [Dosu](https://dosu.dev), and I'm helping the better-auth team manage their backlog and am marking this issue as stale. **Issue Summary** - You reported sorting errors with the MongoDB adapter on unindexed fields in CosmosDB, which requires indexes for sorting. - You provided a detailed list of collections needing a createdAt index to fix this. - Contributors confirmed that adding createdAt indexes resolved the issue. - There is no official list of sortable fields, and the schema's "sortable" label is inconsistently applied. - A suggestion was made to integrate index management into the adapter and improve documentation for CosmosDB support. **Next Steps** - Please let me know if this issue is still relevant with the latest version of better-auth by commenting here. - If I don’t hear back within 7 days, I will automatically close this issue. Thanks for your understanding and contribution!
Author
Owner

@ryami333 commented on GitHub (Mar 5, 2026):

@dosubot still relevant

<!-- gh-comment-id:4006380075 --> @ryami333 commented on GitHub (Mar 5, 2026): @dosubot still relevant
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#10250