当尝试建立与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的问题。
您提供的任何帮助都将不胜感激。
1条答案
按热度按时间6bc51xsx1#
你把调试
放错地方了应该是
即使它在新的一行,
.on
仍然引用mongoose.connection
。你不能只是在中间插入一个新的命令并期望它工作。更新:
“Invalid scheme”错误与此无关,也不是将
console.log
放在代码中任何位置的借口。请检查错误的回溯,它在发生的地方有行号-将console.log
放在那里,例如连接url来自环境变量
MONGODB_URI
或.env
文件,前者优先。