微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在连接打开一次的打字稿中建立mongodb NodeJS驱动程序连接

如何解决如何在连接打开一次的打字稿中建立mongodb NodeJS驱动程序连接

我一直收到连接超时或这封电子邮件 您收到这封警报电子邮件是因为与您的集群的连接已超过 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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。