skip to Main Content

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!

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search