问题描述
我一直收到连接超时或这封电子邮件 您收到这封警报电子邮件是因为与您的集群的连接已超过 500,并且接近项目中 M0 集群 Cluster0 的连接限制 ---- -- 在组织内 ------- 组织 - ------。请重新启动您的应用程序或登录您的 Atlas 帐户以查看一些建议的解决方案。
这是我的连接
import { MongoClient } from "mongodb";
import config from "../config/config";
const { dbname,mongoDBUri } = config;
async function connectToDatabase() {
const connectionoptions = {
useNewUrlParser: true,useUnifiedTopology: true,};
const client = await MongoClient.connect(
mongoDBUri as string,connectionoptions
);
return {
client,db: client.db(dbname),};
}
export default connectToDatabase;
import connectToDatabase from "./../databases/database";
/**
* @async
* @static
* @params
*/
static notifyAllAdmins = async ({
title,link,linkButtonText,message,}: NotifyAllAdminsI) => {
const { client } = await connectToDatabase();
const notificationSchema = {
title,timestamp: Date.Now(),status: {
isDeleted: false,isRead: false,},};
const result = await client
.db("notifications")
.collection("adminAnnouncements")
.insertOne(notificationSchema);
return result.insertedId;
};
现在我的问题是每次我调用连接到数据库时都会创建一个新连接,我希望创建一个连接,随后调用 connectToDatabase 使用现有连接
这我可以用下面的代码用javascript来做
解决方法
经过多次尝试,找到了最适合我的解决方案
import { MongoClient,Db } from "mongodb";
const { dbName,mongoDBUri } = config;
if (!mongoDBUri) {
throw new Error(
"Define the mongoDBUri environment variable inside .env"
);
}
if (!dbName) {
throw new Error(
"Define the dbName environment variable inside .env"
);
}
type MongoConnection = {
client: MongoClient;
db: Db;
};
declare global {
namespace NodeJS {
interface Global {
mongodb: {
conn: MongoConnection | null;
promise: Promise<MongoConnection> | null;
};
}
}
}
let cached = global.mongodb;
if (!cached) {
cached = global.mongodb = { conn: null,promise: null };
}
export default async function connectToDatabase() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
console.log("Establishing new database connection");
const opts = {
useNewUrlParser: true,useUnifiedTopology: true,};
cached.promise = MongoClient.connect(mongoDBUri as string,opts).then(
(client) => {
return {
client,db: client.db(dbName),};
}
);
}
cached.conn = await cached.promise;
return cached.conn;
}