NextJs TypeError: Cannot read properties of undefined (reading '0')

NextJs TypeError: Cannot read properties of undefined (reading '0')

我正在尝试连接到 Mongodb 以定义连接、断开连接并在 API 中使用它。我收到无法读取未定义属性(读取“0”)的类型错误。我控制台检查数组是否包含与此 Mongoose 实例关联的所有连接但只有 0 而不是连接列表。下面是代码片段。

import mongoose from 'mongoose';

const connection = {};

async function connect() {
  if (connection.isConnected) {
    console.log('already connected');
  }
  if (mongoose.connections.length > 0) {
    connection.isConnected = mongoose.connections[0].readyState;
    console.log('cone', connection.isConnected);
    if (connection.isConnected === 1) {
      console.log('use previous connection');
      return;
    }
    await mongoose.disconnect();
  }
  const dbConnect = mongoose.connect(process.env.MONGODB_URI, {
    //   useNewUrlParser: true,
    useUnifiedTopology: true,
    //   useCreateIndex: true,
  });
  console.log('new connection');
  connection.isConnected = dbConnect.connections[0].readyState;
}
async function disconnect() {
  if (connection.isConnected) {
    if (process.env.NODE_ENV === 'production') {
      await mongoose.disconnect();
      connection.isConnected = false;
    } else {
      console.log('not disconnected');
    }
  }
}
const db = { connect, disconnect };
export default db;

我得到的错误是这样的

error - (api)\utils\db.js (25:49) @ Object.connect
TypeError: Cannot read properties of undefined (reading '0')
  23 |   });
  24 |   console.log('new connection');
> 25 |   connection.isConnected = dbConnect.connections[0].readyState;
     |                                                 ^
  26 |   console.log("cone1", connection.isConnected);
  27 | }

mongoose.connect() 上没有类型作为连接。所以只需要删除我正在寻找的连接[0].readyState。

import mongoose from 'mongoose';

const connection = {};

async function connect() {
  if (connection.isConnected) {
    console.log('already connected');
    return;
  }
  if (mongoose.connections.length > 0) {
    connection.isConnected = mongoose.connections[0].readyState;
    if (connection.isConnected === 1) {
      console.log('use previous connection');
      return;
    }
    await mongoose.disconnect();
  }
  const options = {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  };
  const uri = process.env.MONGODB_URI;
  const db = mongoose.connect(uri, options);
  console.log('new connection');
  connection.isConnected = db

  if (!uri) {
    throw new Error('Add your Mongo URI to .env');
  }
}

async function disconnect() {
  if (connection.isConnected) {
    if (process.env.NODE_ENV === 'production') {
      await mongoose.disconnect();
      connection.isConnected = false;
    } else {
      console.log('not disconnected');
    }
  }
}
const db_export = { connect, disconnect };
export default db_export;