12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- // dbConnect.js
- import mongoose from "mongoose";
- const MONGODB_URI = process.env.MONGODB_URI;
- const DB_NAME = process.env.MONGODB_DB_NAME || "mydatabase"; // 添加数据库名称
- if (!MONGODB_URI) {
- throw new Error(
- "Please define the MONGODB_URI environment variable inside .env.local"
- );
- }
- let cached = global.mongoose;
- if (!cached) {
- cached = global.mongoose = { conn: null, promise: null };
- }
- async function dbConnect() {
- if (cached.conn) {
- return cached.conn;
- }
- if (!cached.promise) {
- const opts = {
- bufferCommands: false,
- dbName: DB_NAME, // 明确指定数据库名称
- useNewUrlParser: true,
- useUnifiedTopology: true,
- };
- cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
- console.log(`Connected to MongoDB database: ${DB_NAME}`);
- return mongoose;
- });
- }
- try {
- cached.conn = await cached.promise;
- } catch (e) {
- cached.promise = null;
- console.error("Failed to connect to MongoDB:", e);
- throw e;
- }
- return cached.conn;
- }
- export default dbConnect;
|