Express中无法使用.env文件密码连接MongoDB的问题求助
为何无法在Express中使用.env文件存储的密码连接MongoDB数据库?
你的代码里存在两个关键问题导致连接失败:
1. 字符串模板使用错误
MongoDB连接地址用双引号包裹,导致${password}无法被解析为变量值,必须使用**反引号(`)**来启用模板字符串功能,才能正确注入.env里的密码变量。
2. 变量拼写错误
错误提示里写的是PASSWARD,但你.env里的键是PASSWORD,拼写不一致会导致判断逻辑误触发。
修正后的代码:
const express=require('express'); const mongoose=require('mongoose'); const Product=require('./models/product.model.js'); const app=express(); require("dotenv").config(); app.use(express.json()); const password = process.env.PASSWORD; if(password) { console.log(password); } if (!password) { console.error('Error: PASSWORD is not defined in the .env file'); // 修正拼写错误 process.exit(1); } // 使用反引号包裹连接地址,解析模板变量 mongoose.connect(`mongodb+srv://admin:${password}@backenddb.nb0lnik.mongodb.net/Node-API?retryWrites=true&w=majority&appName=BackendDB`) .then(()=>{ console.log("connected to the Database :)"); app.listen(3000,()=>{ console.log("server running on port 3000"); }) }).catch(err => { console.error('Database connection error:', err); })
额外注意事项:
.env文件中密码不需要加引号,直接写:PASSWORD=你的实际数据库密码- 确认已安装
dotenv包,未安装则执行:npm install dotenv
内容的提问来源于stack exchange,提问作者shivam singh
相关产品推荐
相关产品推荐

