Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
Error: Cannot read properties of undefined (reading 'host')

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();
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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();
});
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!