Home > Net >  TypeError: Cannot read properties of undefined (reading 'host')
TypeError: Cannot read properties of undefined (reading 'host')

Time:06-08

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!

CodePudding user response:

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.

CodePudding user response:

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;
  • Related