部署我的API,然后尝试向DB发送GET请求,结果是Runtime.UnhandledPromiseRejection
Invalid scheme, expected connection string to start with "mongodb:" or "mongodb+srv://
我的db.js
import mongoose from "mongoose";
mongoose.Promise = global.Promise;
mongoose.set("strictQuery", false);
let connection_uri = process.env.MONGODB_URI;
let cachedMongoConn = null;
export const connectToDatabase = () => {
return new Promise((resolve, reject) => {
// mongoose.Promise = global.Promise;
mongoose.connection
.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);
}
});
};
.env
MONGODB_URI=mongodb+srv://Username:Password:...
所有内容看起来都是正确的,.env文件中的连接字符串格式也是正确的。所以我不知道问题出在哪里。
你能提供的任何帮助都将不胜感激。
1条答案
按热度按时间tv6aics11#
我只是有这个相同的问题,删除URI链接之前的引号,解决了它。
问题是变量的格式很可能不正确。
删除空格、引号和结尾处的分号。
这
变成了这样
dev mikeym
那么连接应该可以了