just a beginner in nodeJS, and I encountered this problem.
Server is running on http://localhost:8080
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.
at Connection.openUri (C:SimpleChatAppnode_modulesmongooselibconnection.js:694:11)
at C:SimpleChatAppnode_modulesmongooselibindex.js:380:10
at C:SimpleChatAppnode_modulesmongooselibhelperspromiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (C:SimpleChatAppnode_modulesmongooselibhelperspromiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (C:SimpleChatAppnode_modulesmongooselibindex.js:1225:10)
at Mongoose.connect (C:SimpleChatAppnode_modulesmongooselibindex.js:379:20)
at connectDB (C:SimpleChatAppserverdatabaseconnection.js:4:36)
at Object.<anonymous> (C:SimpleChatAppserver.js:14:1)
at Module._compile (node:internal/modules/cjs/loader:1120:14)
[nodemon] app crashed - waiting for file changes before starting...
this is my server.js
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const bodyparser = require('body-parser');
const path = require('path');
const connectDB = require('./server/database/connection');
const app = express();
const PORT = process.env.PORT||8080
app.use(morgan('tiny'));
connectDB();
app.use(bodyparser.urlencoded({ extended: true }));
app.set("view engine", "ejs");
app.listen(PORT, () => { console.log('Server is running on http://localhost:${PORT}') });
and here is my connection.js
const mongoose = require('mongoose');
const connectDB = async () => {
try{
const con = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
console.log('Database Connected: ${con.connection.host}');
}catch(err){
console.log(err);
process.exit(1);
}
}
module.exports = connectDB
and my env file
PORT=3000
MONGO_URI=mongodb+srv://admin:[email protected]/mydb?retryWrites=true&w=majority
hope you guys can help me. I am really stuck with this. Already tried to look for answers to the problems here in StackOverflow but it seems like not working with me or I am doing it wrong. Thank you in advance!
2
Answers
You have to make a config connection to your .env file. Try a module like dotenv
From the dotenv docs:
Also, the console.log of the ‘Server is running on localhost:${PORT}’" is incorrect syntax. it should be a string template with back ticks:
Same goes for the console.log in your connection file
It seems like the connection string isn’t being read from your
.env
file, hence theundefined
error.You may have forgotten to call the
.config()
after yourdotenv
import.Wherever you use these environment variables, be sure to include this line above it.