方案无效,要求连接字符串以“mongodb:”或“mongodb+srv://”开头

ntjbwcob  于 2023-06-29  发布在  Go
关注(0)|答案(1)|浏览(277)

部署我的API,然后尝试向DB发送GET请求,结果是Runtime.UnhandledPromiseRejectionInvalid 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文件中的连接字符串格式也是正确的。所以我不知道问题出在哪里。
你能提供的任何帮助都将不胜感激。

tv6aics1

tv6aics11#

我只是有这个相同的问题,删除URI链接之前的引号,解决了它。
问题是变量的格式很可能不正确。
删除空格、引号和结尾处的分号。

CONNECTION_URL =
"mongodb+srv://<UserName>:<Password>@cluster0.v5qzigz.mongodb.net/?retryWrites=true&w=majority";

变成了这样

CONNECTION_URL=mongodb+srv://<UserName>:<Password>@cluster0.v5qzigz.mongodb.net/?retryWrites=true&w=majority

dev mikeym
那么连接应该可以了

相关问题