Whenever I try to run node index.js, I am getting "Error [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"
Also, index.js and .env are in the same directory.
index.js:
const express = require('express');
require('dotenv').config();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/api');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
mongoose.connect(process.env.DB, { useNewUrlParser: true })
.then(() => console.log(`Database connected successfully`))
.catch(err => console.log(err));
mongoose.Promise = global.Promise;
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json());
app.use('/api', routes);
app.use((err, req, res, next) => {
console.log(err);
next();
});
app.listen(port, () => {
console.log(`Server running on port ${port}`)
});
.env:
NODE_ENV = development
PORT = 3000
MONGO_URI = mongodb+srv://"User":1@cluster0.da5tj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
I was having same issue and this worked for me. Require in dotenv.
require('dotenv').config()
...and setting the .env file with variable MONGO_URI = my database connection
...and finally making sure to pass the following into mongoose.connect:
process.env.MONGO_URI
Hope that helps. I am noob, so don't count on me being able to answer many questions.
You are having just a little error here but here is the fix, your .env stores your connection string as MONGO_URI and your main code is calling process.env.DB which causes the mongoose error you are getting, i have run your code with my db and its working fine your code should be like below without changing your .env file
const express = require('express');
require('dotenv').config();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/api');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true })
.then(() => console.log(`Database connected successfully`))
.catch(err => console.log(err));
mongoose.Promise = global.Promise;
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json());
app.use('/api', routes);
app.use((err, req, res, next) => {
console.log(err);
next();
});
app.listen(port, () => {
console.log(`Server running on port ${port}`)
});