ai-bot/app/_lib/mongodb.ts

34 lines
1.0 KiB
TypeScript

// lib/mongodb.ts
import { MongoClient, Db } from 'mongodb';
const uri = process.env.MONGODB_URI;
let client: MongoClient;
let clientPromise: Promise<MongoClient>;
if (!uri) {
throw new Error('Please add your Mongo URI to.env.local');
}
if (process.env.NODE_ENV === 'development') {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri);
clientPromise = client.connect();
}
export const getDb = async (): Promise<Db> => {
const client = await clientPromise;
return client.db('ai-bot');
};
export const getCollection = async (collection: string) => {
const client = await clientPromise;
return client.db('ai-bot').collection(collection);
};