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

247
Views
TypeError: Cannot read properties of undefined (reading 'host')

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You should await mongoose.connect which returns a Promise:

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      //   useFindAndModify: false,
    });
    console.log(`MongoDB connecteed: ${conn.connection.host}`);
  } catch (err) {
    console.error(err);
    process.exit(1);
  }
};

module.exports = connectDB;
about 4 years ago · Juan Pablo Isaza Report

0

The error is likely because conn.connection is null, and you're trying to access the property host on it.

Try logging conn rather than conn.connection.host.

about 4 years ago · Juan Pablo Isaza 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!