mongodb mongoose.connection无法读取未定义的属性(阅读“on”)

xlpyo6sf  于 2023-01-12  发布在  Go
关注(0)|答案(1)|浏览(176)

当尝试建立与atlas中DB的连接时,我得到Cannot read properties of undefined (reading 'on')
db.js

import mongoose from "mongoose";
import dotenv from "dotenv";
mongoose.Promise = global.Promise;
mongoose.set("strictQuery", false);

dotenv.config()

let connection_uri = process.env.MONGODB_URI;
let cachedMongoConn = null;

export const connectToDatabase = () => {
  return new Promise((resolve, reject) => {
    //mongoose.Promise = global.Promise;
    mongoose.connection
    console.log(mongoose.connect)
      .on("error", (error) => {
        console.log("Error: connection to DB failed");
        reject(error);
      })
      .on("close", () => {
        console.log("Error: Connection to DB lost");
        process.exit(1);
      })
      // Connected to DB
      .once("open", () => {
        // Display connection information
        const infos = mongoose.connections;

        infos.map((info) =>
          console.log(`Connected to ${info.host}:${info.port}/${info.name}`)
        );
        // Return successful promise
        resolve(cachedMongoConn);
      });
    if (!cachedMongoConn) {
      cachedMongoConn = mongoose.connect(connection_uri, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        connectTimeoutMS: 60000,
        bufferCommands: false, 
      });
    } else {
      console.log("MongoDB: using cached database instance");
      resolve(cachedMongoConn);
    }
  });
};

注解掉两个.on后,我在.once上得到了相同的错误
不知道为什么我与mongoose.connection的连接有问题,也许是ES6的问题。
您提供的任何帮助都将不胜感激。

6bc51xsx

6bc51xsx1#

你把调试

console.log(mongoose.connect)

放错地方了应该是

mongoose.connection
  .on("error", (error) => {

即使它在新的一行,.on仍然引用mongoose.connection。你不能只是在中间插入一个新的命令并期望它工作。

更新

“Invalid scheme”错误与此无关,也不是将console.log放在代码中任何位置的借口。请检查错误的回溯,它在发生的地方有行号-将console.log放在那里,例如

if (!cachedMongoConn) {
  console.log(connection_uri)
  cachedMongoConn = mongoose.connect(connection_uri, {

连接url来自环境变量MONGODB_URI.env文件,前者优先。

相关问题