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:\SimpleChatApp\node_modules\mongoose\lib\connection.js:694:11)
at C:\SimpleChatApp\node_modules\mongoose\lib\index.js:380:10
at C:\SimpleChatApp\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\SimpleChatApp\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (C:\SimpleChatApp\node_modules\mongoose\lib\index.js:1225:10)
at Mongoose.connect (C:\SimpleChatApp\node_modules\mongoose\lib\index.js:379:20)
at connectDB (C:\SimpleChatApp\server\database\connection.js:4:36)
at Object.<anonymous> (C:\SimpleChatApp\server.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:admin@cluster0.nirfnsf.mongodb.net/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!
>Solution :
You have to make a config connection to your .env file. Try a module like dotenv
From the dotenv docs:
require('dotenv').config()
console.log(process.env) // remove this after you've confirmed it working
Also, the console.log of the ‘Server is running on localhost:${PORT}’" is incorrect syntax. it should be a string template with back ticks:
console.log(`Server is running on http://localhost:${PORT}`)
Same goes for the console.log in your connection file