You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用.env文件后MongoDB连接失败问题求助

React应用连接MongoDB的.env配置问题

之前在db.js文件中硬编码MongoDB连接字符串时可正常建立连接,改用.env文件配置连接信息后,运行node server.js时出现以下错误:

/Users/home/Developer Files/inkbucket/server/node_modules/mongodb-connection-string-url/lib/index.js:9
    return (connectionString.startsWith('mongodb://') ||
                             ^

TypeError: Cannot read properties of undefined (reading 'startsWith')
    at connectionStringHasValidScheme (/Users/home/Developer Files/inkbucket/server/node_modules/mongodb-connection-string-url/lib/index.js:9:30)
    at new ConnectionString (/Users/home/Developer Files/inkbucket/server/node_modules/mongodb-connection-string-url/lib/index.js:85:34)
    at parseOptions (/Users/home/Developer Files/inkbucket/server/node_modules/mongodb/lib/connection_string.js:197:17)
    at new MongoClient (/Users/home/Developer Files/inkbucket/server/node_modules/mongodb/lib/mongo_client.js:46:63)
    at Object.<anonymous> (/Users/home/Developer Files/inkbucket/server/server.js:4:16)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Module._load (node:internal/modules/cjs/loader:922:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)

Node.js v18.13.0

涉及的文件内容

可正常连接的db.js(未使用.env)

const MongoClient = require("mongodb").MongoClient;
const uri =
  "mongodb+srv://wynter:fakepassword@inkbucket.dvufxul.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect((err) => {
  if (err) {
    console.log("Unable to connect to MongoDB");
  } else {
    console.log("Connected to DB");
  }
});

无法连接的db.js(使用.env)

require("dotenv").config();
const MongoClient = require("mongodb").MongoClient;
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect((err) => {
  if (err) {
    console.log("Unable to connect to MongoDB");
  } else {
    console.log("Connected to DB");
  }
});

server.js

require("dotenv").config();
const express = require("express");
const app = express();
const port = process.env.PORT || 8080;
const db = require("./db");

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

.env文件

MONGODB_URI="mongodb+srv://wynter:fakepassword@inkbucket.dvufxul.mongodb.net/?retryWrites=true&w=majority"

问题原因及解决办法

报错核心是process.env.MONGODB_URI为undefined,说明.env中的变量未被正确加载或读取,按以下步骤排查:

  • 移除.env中的引号:当前.env里的连接字符串包含双引号,dotenv会将引号作为变量值的一部分,导致连接字符串无效。修改后:

    MONGODB_URI=mongodb+srv://wynter:fakepassword@inkbucket.dvufxul.mongodb.net/?retryWrites=true&w=majority
    
  • 检查.env文件位置:确保.env文件和server.js处于同一目录(项目根目录),如果放在子目录,需要在dotenv.config()中指定路径:require("dotenv").config({ path: "./your/subfolder/.env" })

  • 确认dotenv安装与加载顺序:先执行npm install dotenv确保依赖安装,且require("dotenv").config()必须在读取process.env变量之前执行。可以统一在server.js最顶部加载dotenv,避免db.js重复加载导致的问题。

  • 校验变量名拼写:确保.env中的变量名MONGODB_URI和代码中读取的名称完全一致,环境变量名大小写敏感。

  • 重启服务器:修改.env文件后必须重启node server.js,否则新的环境变量不会生效。

内容的提问来源于stack exchange,提问作者ransomenote

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:25:50