1

我不断收到连接超时或此电子邮件您收到此警报电子邮件是因为与您的集群的连接已超过 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,
      link,
      linkButtonText,
      message,
      timestamp: Date.now(),
      status: {
        isDeleted: false,
        isRead: false,
      },
    };
    const result = await client
      .db("notifications")
      .collection("adminAnnouncements")
      .insertOne(notificationSchema);
    return result.insertedId;
  };

现在我的问题是每次我调用连接到数据库时都会创建一个新连接,我希望创建一个连接,随后调用 connectToDatabase 将使用现有连接

这我可以用下面的代码用javascript做


4

1 回答 1

0

经过几次在这里尝试后,最适合我的解决方案

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;
}
于 2021-07-25T05:59:06.390 回答