mongoose.connection.readyState导致TypeError:无法读取undefined的属性(阅读“readyState”)

uyto3xhc  于 2023-05-29  发布在  Go
关注(0)|答案(2)|浏览(351)

我一直在使用Mongo内存服务器进行单元测试,它一直工作得很好,但现在mongoose.connection是未定义的,我完全不知道为什么!我希望readyState至少返回0。

import * as mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';

let con: mongoose.Connection;
let mongoServer: MongoMemoryServer;

export const connectDB = async () => {
  mongoServer = await MongoMemoryServer.create();
  await mongoose.connect(mongoServer.getUri(), {})
  .catch((err) => {
    console.log(err); // no error is thrown
  });
  con = mongoose.connection; // undefined, but why?!
  console.log(con.readyState); // this line is triggering the error
}
cnjp1d6j

cnjp1d6j1#

esModuleInterop: true或在tsconfig.json中未设置时,使用默认导入import mongoose from 'mongoose'
esModuleInterop: false或在tsconfig.json中未设置时,使用命名空间导入import * as mongoose from 'mongoose'

import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';

let con: mongoose.Connection;
let mongoServer: MongoMemoryServer;

export const connectDB = async () => {
  mongoServer = await MongoMemoryServer.create();
  await mongoose.connect(mongoServer.getUri(), {})
    .catch((err) => {
      console.log(err);
    });
  con = mongoose.connection;
  console.log('con.readyState: ', con.readyState);
}

connectDB();

日志:

⚡  npx ts-node ./index.ts
con.readyState:  1

软件包版本:

"mongodb-memory-server": "^8.12.2",
"mongoose": "^7.1.1",
bqujaahr

bqujaahr2#

import * as mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';

let con: mongoose.Connection;
let mongoServer: MongoMemoryServer;

export const connectDB = async () => {
  mongoServer = await MongoMemoryServer.create();
  await mongoose.connect(mongoServer.getUri(), {})
  .catch((err) => {
    console.log(err);
  });
  con = mongoose.connections[0];
  console.log(con.readyState);
}

我通过如上所述将mongoose.connection切换到mongoose.connections [0]解决了这个问题。我不确定这是mongoose 7.2.0的问题还是我的工作区配置的问题。

相关问题