问题描述
我正在将我的MERN应用程序部署到Digital Ocean Droplet(Ubuntu 20.04服务器)上.
I am in the process of deploying my MERN app to a Digital Ocean droplet (Ubuntu 20.04 server).
我已经将GitHub存储库克隆到了Droplet,并使用 npm install
安装了依赖项.接下来,当我使用 npm start
启动服务器时,出现以下错误:
I have cloned my GitHub repo to the droplet, installed the dependencies using npm install
. Next, when I am starting the server using npm start
, I get the following error:
该错误实质上表明 mongoose.connect()
的第一个参数是未定义的,必须为字符串.但是,在我的本地计算机上一切正常,当我console.log process.env.MONGO_URI
时,我得到了连接字符串.
The error essentially says that the first parameter to mongoose.connect()
is undefined and must be a string. However, everything works fine in my local machine and when I console.log process.env.MONGO_URI
, I get the connection string.
server/config/db.js
server/config/db.js
const mongoose = require("mongoose");
const colors = require("colors");
const dotenv = require("dotenv");
dotenv.config();
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
console.log(`MongoDB connected: ${conn.connection.host}`.cyan.bold);
} catch (error) {
console.error(`Error: ${error.message}`.red.bold.underline);
process.exit(1);
}
};
2;
module.exports = connectDB;
为什么在Digital Ocean Droplet中启动服务器时出现此错误?
Why am I getting this error while starting the server in my Digital Ocean droplet?
推荐答案
dotenv
不会加载系统变量.
使用
MONGO_URI=XXXXXXX
https://github.com/motdotla/dotenv#usage
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
这篇关于Digital Ocean Droplet中的MongoDB连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!