96 lines
2.8 KiB
JavaScript
96 lines
2.8 KiB
JavaScript
const { MongoClient } = require("mongodb");
|
||
|
||
// 震元堂环境 // 注意后面的配置, 根据实际情况修改
|
||
const username = process.env.CONFIG_DB_USERNAME;
|
||
const password = process.env.CONFIG_DB_PASSWORD;
|
||
const host = process.env.CONFIG_DB_HOST; // 例如:'localhost' 或 MongoDB Atlas提供的连接地址
|
||
|
||
const port = process.env.CONFIG_DB_PORT || "27017"; // MongoDB默认端口为'27017'
|
||
|
||
// 构建连接字符串,包含身份验证信息
|
||
const url = `mongodb://${username}:${password}@${host}:${port}/admin`;
|
||
console.log(`mongoDB url: ${url}`);
|
||
const options = {
|
||
maxPoolSize: 100, // 设置最大连接池大小为 100
|
||
minPoolSize: 10, // 设置最小连接池大小为 10
|
||
connectTimeoutMS: 60000, // 连接超时 60 秒
|
||
socketTimeoutMS: 60000, // 数据传输超时 60 秒
|
||
// useUnifiedTopology 在 MongoDB Driver 4.0+ 中已被废弃,无需设置
|
||
};
|
||
let client;
|
||
let isConnecting = false;
|
||
|
||
async function connectToMongoDB() {
|
||
try {
|
||
console.log("连接 MongoDB");
|
||
if (!client && !isConnecting) {
|
||
isConnecting = true;
|
||
|
||
// 检查必要的环境变量
|
||
if (!username || !password || !host) {
|
||
throw new Error("MongoDB连接参数缺失: 请检查环境变量 CONFIG_DB_USERNAME, CONFIG_DB_PASSWORD, CONFIG_DB_HOST");
|
||
}
|
||
|
||
client = new MongoClient(url, options);
|
||
await client.connect();
|
||
console.log("MongoDB 连接成功");
|
||
isConnecting = false;
|
||
}
|
||
return client;
|
||
} catch (err) {
|
||
isConnecting = false;
|
||
console.error("MongoDB连接失败:", err);
|
||
throw err; // 抛出错误而不是静默失败
|
||
}
|
||
}
|
||
|
||
async function getDatabase(dbName) {
|
||
if (!client) {
|
||
throw new Error("MongoDB客户端未连接,请先调用 connectToMongoDB()");
|
||
}
|
||
|
||
try {
|
||
const db = client.db(dbName);
|
||
// 测试数据库连接
|
||
await db.admin().ping();
|
||
return db;
|
||
} catch (err) {
|
||
console.error(`获取数据库 ${dbName} 失败:`, err);
|
||
throw new Error(`无法访问数据库 ${dbName}: ${err.message}`);
|
||
}
|
||
}
|
||
|
||
async function closeMongoDB() {
|
||
if (client) {
|
||
await client.close();
|
||
client = null;
|
||
}
|
||
}
|
||
|
||
// 检查连接状态
|
||
function isConnected() {
|
||
return client && client.topology && client.topology.isConnected();
|
||
}
|
||
|
||
// exports.connectToMongoDB = async (item, type, dbName) => {
|
||
// try {
|
||
// const db = await getDatabase(dbName);
|
||
// // 获取 serverStatus 的连接数信息
|
||
// const res = await type.main(item, db);
|
||
// return res;
|
||
// } catch (err) {
|
||
// // 细化错误信息
|
||
// return {
|
||
// success: false,
|
||
// message: err.message,
|
||
// };
|
||
// }
|
||
// };
|
||
process.on("SIGINT", async () => {
|
||
console.log("关闭 MongoDB 连接");
|
||
await closeMongoDB();
|
||
process.exit(0);
|
||
});
|
||
|
||
module.exports = { connectToMongoDB, getDatabase, closeMongoDB, isConnected };
|