【问题标题】:Mongodb Typescript UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'conn' of undefined at Object.connectToDatabase [as default]Mongodb Typescript UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'conn' of undefined at Object.connectToDatabase [as default]
【发布时间】:2021-07-25 13:55:47
【问题描述】:

typescript连接mongo数据库报错,全局声明conn后可以读取未定义的conn

UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“conn” 在 Object.connectToDatabase [默认]

import { MongoClient, Db } from "mongodb";
import config from "../config/config";
const { dbName, mongoDBUri } = config;

type MongoConnection = {
  client: MongoClient;
  db: Db;
};

declare global {
  namespace NodeJS {
    interface Global {
      mongodb: {
        conn: MongoConnection | null;
        promise: Promise<MongoConnection> | null;
      };
    }
  }
}
let cached = global.mongodb;
async function connectToDatabase() {
  if (cached.conn) {
    return cached.conn;
  }

  if (!cached.promise) {
    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;
}

export default connectToDatabase;


【问题讨论】:

  • 很明显,global.mongodb 是未定义的。您必须在某处为其分配一个值。
  • 请问在哪里以及如何将值添加到global.mongodb

标签: node.js typescript mongodb


【解决方案1】:

您可以使用以下设置

//interfaces/db.interface
export interface dbConfig {
    host: string;
    port: number;
    database: string;
    username: string;
    password: string;
}

//database.ts
import { dbConfig } from "@interfaces/db.interface";

const { host, port, database, username, password }: dbConfig = config.get("dbConfig");

export const dbConnection = {
    url: `mongodb://${username}:${password}@${host}:${port}/${database}?authSource=admin`,
    options: {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
        useCreateIndex: true
    },
};


//app.ts (express app)
import { dbConnection } from "@databases";
constructor(routes: Routes[]) {
    this.app = express();
    this.port = process.env.PORT || 5000;
    this.env  = process.env.NODE_ENV || "development";
    this.connectToDatabase();
}
private connectToDatabase() {
    if (this.env !== "production") {
        set("debug", true);
    }
    connect(dbConnection.url, dbConnection.options)
    .catch((error) =>
        console.log(`${error}`)
    );
}

这里我假设您在 tsconfig.json 文件中设置了路径,以便 @ 在导入中起作用。

【讨论】:

    【解决方案2】:

    经过几次尝试,我不得不使用 NextJs MongoDB 连接模式并将其转换为 typescript,它工作得非常好

    import config from "./../config/config";
    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;
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 2023-01-19
      • 2019-05-26
      • 2021-06-25
      • 2020-09-04
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      相关资源
      最近更新 更多