Im keep getting that error while having no idea why. Im trying to connect to my mongodb database but it keeps telling me that "host" is undefined!
Here are my files:
Index.js
const express = require("express");
const dotenv = require("dotenv");
const connectDB = require("./config/db");
//Load config
dotenv.config({ path: "./config/config.env" });
console.log("hello");
connectDB();
const app = express();
const PORT = process.env.PORT || 3000;
app.listen(
PORT,
console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);
The error is in db.js line 11
const mongoose = require("mongoose");
const connectDB = async () => {
try {
const conn = mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
// useFindAndModify: false,
});
console.log("hey!");
console.log(`MongoDB connecteed: ${conn.connection.host}`);
} catch (err) {
console.error(err);
process.exit(1);
}
};
module.exports = connectDB;
Please let me know if im missing anything.
Thank you!
2
Answers
The error is likely because
conn.connection
is null, and you’re trying to access the propertyhost
on it.Try logging
conn
rather thanconn.connection.host
.You should
await
mongoose.connect
which returns aPromise
: