ai-bot/app/_lib/mongodb.ts

32 lines
822 B
TypeScript

// lib/mongodb.ts
import { MongoClient, Db } from 'mongodb';
const uri = process.env.MONGODB_URI;
const options = {};
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') {
if (!(global as any)._mongoClientPromise) {
client = new MongoClient(uri, options);
(global as any)._mongoClientPromise = client.connect();
}
clientPromise = (global as any)._mongoClientPromise;
} else {
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
export const getDb = async () => {
return (await clientPromise).db('ai-bot');
};
export const getCollection = async (collection: string) => {
const ins = await getDb();
return ins.collection(collection);
};