Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

75
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!

8 months 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;
8 months 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.

8 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs