Node.js 我在将env连接到mongoose时出错
这在我的.env文件中Node.js 我在将env连接到mongoose时出错,node.js,express,Node.js,Express,这在我的.env文件中 DB_URL=mongodb://localhost:27017/ecomm 而connection.js文件是 const mongoose=require('mongoose') const {DB_URL}=process.env console.log(process.env) async function createConnection(){ console.log("create connection") const
DB_URL=mongodb://localhost:27017/ecomm
而connection.js文件是
const mongoose=require('mongoose')
const {DB_URL}=process.env
console.log(process.env)
async function createConnection(){
console.log("create connection")
const connection=await mongoose.connect(DB_URL,{
useNewUrlParser:true,useUnifiedTopology:true,useCreateIndex: true
})
if (connection){
console.log("connected")
}
}
但我得到的错误是
(node:2304) UnhandledPromiseRejectionWarning: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
为什么我会出错?
const{DB_URL}=process.env
console.log({DB_URL})在控制台中未定义showm使用dotenv包 在连接文件中
require('dotenv').config();
connectDB();
function connectDB(){
// mongoose.set('useCreateIndex', true)
mongoose.connect(process.env.MONGODB_URI // your uriName,
{
useNewUrlParser: true,
poolSize: 20,
keepAlive: 300000,
reconnectTries:1000,
reconnectInterval: 90000
},function(err, db){
if(err){
console.log("Error in Connectiion to DB : ",err);
setTimeout(()=>{
connectDB();
},5000)
}else{
return(db);
}
}); // database conneciton to azure pro database
mongoose
.connection
.once('connected', () => console.log('Connected to database'));
}```
then use this code to connect it will also auto retry if connection fails
使用dotenv包 在连接文件中
require('dotenv').config();
connectDB();
function connectDB(){
// mongoose.set('useCreateIndex', true)
mongoose.connect(process.env.MONGODB_URI // your uriName,
{
useNewUrlParser: true,
poolSize: 20,
keepAlive: 300000,
reconnectTries:1000,
reconnectInterval: 90000
},function(err, db){
if(err){
console.log("Error in Connectiion to DB : ",err);
setTimeout(()=>{
connectDB();
},5000)
}else{
return(db);
}
}); // database conneciton to azure pro database
mongoose
.connection
.once('connected', () => console.log('Connected to database'));
}```
then use this code to connect it will also auto retry if connection fails
在这条线上,
const {DB_URL}=process.env
您使用的是process.env对象,而不是正确的变量字符串。mongoose.connect获取字符串URL。请更正。在这一行
const {DB_URL}=process.env
您使用的是process.env对象,而不是正确的变量字符串。mongoose.connect获取字符串URL。请更正。您是否在代码中的某个地方使用了
dotenv
包?您需要它来从节点进程中复制的.env文件中获取环境变量。您是否在代码中的某个地方使用了dotenv
包?您需要它来从节点进程中复制的.env文件中获取环境变量。