I am trying to connect my application to MongoDB, but getting this error 'Error: Cannot read properties of undefined (reading 'host')'. Not able to figure out what might be the problem.
Here is the .env file
PORT=5000;
MONGO_URI ='mongodb srv://sakshi_0630:<password>@cluster0.lxchu.mongodb.net/?retryWrites=true&w=majority'
db.js file
const mongoose = require("mongoose");
const colors = require("colors");
const connectDB=async()=>{
try {
const conn = mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
});
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline);
} catch (error) {
console.log(`Error: ${error.message}`.red.bold);
process.exit();
}
};
module.exports= connectDB;
server.js
const { response } = require("express");
const express = require("express");
const dotenv = require("dotenv");
const { chats } = require("./data/data");
const connectDB = require("./config/db");
dotenv.config();
connectDB();
const app = express();
CodePudding user response:
You need to await
the mongoose.connect()
function
const connectDB = async() => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
});
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline);
} catch (error) {
console.log(`Error: ${error.message}`.red.bold);
process.exit();
}
};
or use a callback function
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
})
.then((conn) => {
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline);
//do other things
})
.catch((error) => {
console.log(`Error: ${error.message}`.red.bold);
process.exit();
});