连接到MongoDB时出错:MongooseServerSelectionError

kxkpmulp  于 2023-10-16  发布在  Go
关注(0)|答案(1)|浏览(217)

我在尝试使用Mongoose将Node.js应用程序连接到MongoDB时遇到了一个问题。每当我尝试启动应用程序时,都会收到以下错误:
连接到MongoDB时出错:MongooseServerSelectionError:getaddrinfo ENOTFOUND mongodb下面是我用来建立连接的代码片段:

const mongoose = require("mongoose");
require("dotenv").config();

const user = process.env.MONGODB_USER;
const pwd = process.env.MONGODB_PWD;
const host = "mongodb://localhost:27017";
const database = "todoList";

const connectionString = `mongodb://${user}:${pwd}@${host}/${database}`;

mongoose
    .connect(connectionString, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    .then(() => {
        console.log("Conectado ao banco de dados");
    })
    .catch((err) => {
        console.error("Erro ao conectar ao banco de dados", err);
        process.exit();
    });

I've already checked my MONGODB_USER and MONGODB_PWD environment variables, and they are set correctly. Also, I'm sure the MongoDB server is running.

Alguém pode me ajudar a identificar o que pode estar causando esse erro de conexão e como posso resolvê-lo? Agradeço antecipadamente pela ajuda!
ryevplcw

ryevplcw1#

修改host变量如下:

const host = "mongodb://localhost:27017";

这是:

const host = "localhost:27017";

当你把这个插入到你的连接字符串中时:

const connectionString = `mongodb://username:password@mongodb://localhost:27017/todoList`;

但你想要的是:

const connectionString = `mongodb://username:password@localhost:27017/todoList`;

相关问题