I am setting up my database connection using a MEVN stack but I am getting the following error;
The `uri` parameter to `openUri()` must be a string, got "undefined"
If I try console log process.env.DATABASE_URL it just returns undefined. What have I done wrong here's my code;
index.js
import dotenv from 'dotenv';
import Express from 'express';
import Mongoose from 'mongoose';
dotenv.config();
const app = Express();
Mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true });
app.listen(3000, () => {
// console.log(process.env.DATABASE_URL);
console.log('server started on port 3000');
});
.env
DATABASE_URL="mongodb+srv://reece:<password>@mevn-tutorial-cluster-egjs6.mongodb.net/auth?retryWrites=true&w=majority"
I removed my password for obvious reasons
You have to create a .env file in the root dir of your application. in the .env file you should have key value separate by equal sign. As example:
secret=foo
DATABASE_URL=bar:pwd@localhost.com
As the documentation states: https://www.npmjs.com/package/dotenv
You have not used template literals for mongoose connections.
Try this:
Mongoose.connect(${process.env.DATABASE_URL}, { useNewUrlParser: true });
to get actual .env
variable to your Javascript snippet.
I made this mistake, and you shouldn't do it either.
Make sure your.env file is in the root. Check the path of.env before proceeding ahead.
npm install dotenv
require("dotenv").config(); //Keep this at top of your file
In.env file, add
ADMIN_ID="mongoose://******************" //YOUR URL ADDRESS WITH PASSWORD
In app.js file,
mongoose.connect(process.env.ADMIN_ID);
It worked for me.
dotenv.config({ path: "config.env" });
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
})
use path. it'll work
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.