BA
Better Auth•4mo ago
kaas

MongoDB

Fresh install nextjs following docs - And using the following for mongodb auth.ts
import { betterAuth } from "better-auth";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { client } from "@/db/index"; // Importing specifically from index

export const auth = betterAuth({
database: mongodbAdapter(client)
});
import { betterAuth } from "better-auth";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { client } from "@/db/index"; // Importing specifically from index

export const auth = betterAuth({
database: mongodbAdapter(client)
});
my db instance index.ts
import { MongoClient } from "mongodb";

const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

export async function connectToDatabase() {
if (!client.isConnected()) {
await client.connect();
}
return client.db("testdb");
}

export { client };
import { MongoClient } from "mongodb";

const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

export async function connectToDatabase() {
if (!client.isConnected()) {
await client.connect();
}
return client.db("testdb");
}

export { client };
"mongodb is not supported" when doing generate. "
30 Replies
kaas
kaasOP•4mo ago
When siging up
bekacru
bekacru•4mo ago
both generate and migrate doesn't work with mongodb you need to pass the collection instance instead
const client = new MongoClient(process.env.MONGO_DB_URI!);
client.connect();
export const db = client.db("testdb");
const client = new MongoClient(process.env.MONGO_DB_URI!);
client.connect();
export const db = client.db("testdb");
Something like this and pass the db to the adpater
mongodbAdapter(db)
mongodbAdapter(db)
kaas
kaasOP•4mo ago
Brain fart. OF course. This fixed it - How does it react when adding plugins? That works aswell?
bekacru
bekacru•4mo ago
yeah
kaas
kaasOP•4mo ago
Just checking in before creating a bug
:
"You are not a member of this organization"
:
"You are not a member of this organization"
Payload in packet
{
"organizationId": "67339195a5578064fb959d19"
}
{
"organizationId": "67339195a5578064fb959d19"
}
add set-active api endpoint However, in "member" see attached pic - The user is the owenr of it.
No description
bekacru
bekacru•4mo ago
this is must be a bug
kaas
kaasOP•4mo ago
I'll create a bug on git
kaas
kaasOP•4mo ago
GitHub
Organization Plugin · Issue #508 · better-auth/better-auth
Describe the bug "You are not a member of this Organization" when trying to set active org for a user that has the owner role on said org. This is using client.organization.setActive({ or...
bekacru
bekacru•4mo ago
wait you need to pass headers to set active org are you passing headers? never mind thought it was auth.api call
kaas
kaasOP•4mo ago
Nop
bekacru
bekacru•4mo ago
You're calling this on the client right? not on the server
kaas
kaasOP•4mo ago
Yes Pls do ping me here if you find anything thats related to it. The app im doing relies heavily on the org addon 😄
bekacru
bekacru•4mo ago
hey, it will be fixed today
kaas
kaasOP•4mo ago
Pls let me know what version I will implement it asap. Sorry! I changed to use Prisma:
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "mongodb",
}),
emailAndPassword: {
enabled: true
}
});
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "mongodb",
}),
emailAndPassword: {
enabled: true
}
});
` Schema looks like
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}

model Product {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
description String?
price Float
imageUrl String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model User {
id String @id @map("_id")
name String
email String
emailVerified Boolean
image String?
createdAt DateTime
updatedAt DateTime

@@unique([email])
@@map("user")
}

model Session {
id String @id @map("_id")
expiresAt DateTime
ipAddress String?
userAgent String?
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@map("session")
}

model Account {
id String @id @map("_id")
accountId String
providerId String
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessToken String?
refreshToken String?
idToken String?
expiresAt DateTime?
password String?

@@map("account")
}

model Verification {
id String @id @map("_id")
identifier String
value String
expiresAt DateTime

@@map("verification")
}
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}

model Product {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
description String?
price Float
imageUrl String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model User {
id String @id @map("_id")
name String
email String
emailVerified Boolean
image String?
createdAt DateTime
updatedAt DateTime

@@unique([email])
@@map("user")
}

model Session {
id String @id @map("_id")
expiresAt DateTime
ipAddress String?
userAgent String?
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@map("session")
}

model Account {
id String @id @map("_id")
accountId String
providerId String
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessToken String?
refreshToken String?
idToken String?
expiresAt DateTime?
password String?

@@map("account")
}

model Verification {
id String @id @map("_id")
identifier String
value String
expiresAt DateTime

@@map("verification")
}
Upon sign up, I get error
ERROR Cannot read properties of undefined (reading 'findFirst') Better Auth
POST /api/auth/sign-up/email?currentURL=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fsign-up 500 in 1869ms
ERROR Cannot read properties of undefined (reading 'findFirst') Better Auth
POST /api/auth/sign-up/email?currentURL=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fsign-up 500 in 1869ms
NextJS 15 with prisma. How come? What am I missing? I followed the docs to use prisma.
bekacru
bekacru•4mo ago
make sure to generate the schema. this should only happen if prisma[modelName].findFirst throws an error.
kaas
kaasOP•4mo ago
I just updated to 0.8.3 beta 5 npx @better-auth/cli generate ERROR Failed to initialize database adapter
No other changes have been done. auth.ts
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "mongodb",
}),
emailAndPassword: {
enabled: true
},
user: {
additionalFields: {
firstName: {
type: "string",
required: false
},
lastName: {
type: "string",
required: false
},
phone: {
type: "string",
required: false
}
}
}
});
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "mongodb",
}),
emailAndPassword: {
enabled: true
},
user: {
additionalFields: {
firstName: {
type: "string",
required: false
},
lastName: {
type: "string",
required: false
},
phone: {
type: "string",
required: false
}
}
}
});
db.ts
import { PrismaClient } from '@prisma/client'

const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}

export const prisma = globalForPrisma.prisma ?? new PrismaClient()

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
import { PrismaClient } from '@prisma/client'

const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}

export const prisma = globalForPrisma.prisma ?? new PrismaClient()

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
It worked just before I updated 😛
bekacru
bekacru•4mo ago
use the latest cli there was a breaking change
kaas
kaasOP•4mo ago
How would I get that downloaded?
bekacru
bekacru•4mo ago
npx @better-auth/cli@latest generate if incase this is being cached npx @better-auth/[email protected] generate
kaas
kaasOP•4mo ago
error: unknown command 'generate@latest'
PS C:\Users\Kevin\Documents\Binmate-fullstack> npx @better-auth/cli generate@latest
error: unknown command 'generate@latest'
PS C:\Users\Kevin\Documents\Binmate-fullstack> npx @better-auth/cli generate@latest
Hmm
bekacru
bekacru•4mo ago
oh corrected
kaas
kaasOP•4mo ago
Huh?
bekacru
bekacru•4mo ago
npx @better-auth/cli@latest generate
kaas
kaasOP•4mo ago
Funnily it asks me to install the same
PS C:\Users\Kevin\Documents\Binmate-fullstack> npx @better-auth/cli@latest generate
Need to install the following packages:
@better-auth/[email protected]
PS C:\Users\Kevin\Documents\Binmate-fullstack> npx @better-auth/cli@latest generate
Need to install the following packages:
@better-auth/[email protected]
Which then goes back to
ERROR Failed to initialize database adapter
ERROR Failed to initialize database adapter
bekacru
bekacru•4mo ago
is better-auth version 0.8.3-beta.5 as well?
kaas
kaasOP•4mo ago
no, in package.json
"better-auth": "^0.8.2",
"better-auth": "^0.8.2",
bekacru
bekacru•4mo ago
well update it to latest as well
kaas
kaasOP•4mo ago
Yep. That did solve the issue as seems. -> Does this fix the orgiinal issue about User orgs not being able to set active as reported on git
bekacru
bekacru•4mo ago
yes
kaas
kaasOP•4mo ago
Might be a bug again in the orgs plugin! Let me know if I need to file a bug
const handleCreateOrg = async () => {
try {
await authClient.organization.create({
name: orgFormData.name,
slug: orgFormData.slug,
logo: orgFormData.logo || undefined,
metadata: JSON.stringify({
website: orgFormData.metadata.website,
vatNumber: orgFormData.metadata.vatNumber
})
})

// Reset form
setOrgFormData({
name: "",
slug: "",
logo: "",
metadata: {
website: "",
vatNumber: ""
}
})
} catch (error) {
console.error("Failed to create organization:", error)
}
}
const handleCreateOrg = async () => {
try {
await authClient.organization.create({
name: orgFormData.name,
slug: orgFormData.slug,
logo: orgFormData.logo || undefined,
metadata: JSON.stringify({
website: orgFormData.metadata.website,
vatNumber: orgFormData.metadata.vatNumber
})
})

// Reset form
setOrgFormData({
name: "",
slug: "",
logo: "",
metadata: {
website: "",
vatNumber: ""
}
})
} catch (error) {
console.error("Failed to create organization:", error)
}
}
Returns
{
"message": "[\n {\n \"code\": \"invalid_type\",\n \"expected\": \"object\",\n \"received\": \"string\",\n \"path\": [\n \"metadata\"\n ],\n \"message\": \"Expected object, received string\"\n }\n]",
"details": [
{
"code": "invalid_type",
"expected": "object",
"received": "string",
"path": [
"metadata"
],
"message": "Expected object, received string"
}
]
}
{
"message": "[\n {\n \"code\": \"invalid_type\",\n \"expected\": \"object\",\n \"received\": \"string\",\n \"path\": [\n \"metadata\"\n ],\n \"message\": \"Expected object, received string\"\n }\n]",
"details": [
{
"code": "invalid_type",
"expected": "object",
"received": "string",
"path": [
"metadata"
],
"message": "Expected object, received string"
}
]
}
But as it seems, according to docs, it should be a string not a object. The payload is formatted like
{
"name": "test",
"slug": "test",
"logo": "test",
"metadata": {
"vatNumber": "test",
"website": "test",
"phone": "test",
"email": "[email protected]",
"street": "test",
"zip": "test",
"city": "test",
"country": "test",
"contactPerson": {
"name": "test",
"phone": "test"
}
}
}
{
"name": "test",
"slug": "test",
"logo": "test",
"metadata": {
"vatNumber": "test",
"website": "test",
"phone": "test",
"email": "[email protected]",
"street": "test",
"zip": "test",
"city": "test",
"country": "test",
"contactPerson": {
"name": "test",
"phone": "test"
}
}
}
If I assign one value to metadata, e'g vatnumber - It works fine

Did you find this page helpful?