Search code examples
javascriptnode.jsmongodbexpressmongoose

How to resolve "TypeError: connectDB is not a function" in Node.js?


I encountered a TypeError when trying to connect to MongoDB using Mongoose in a Node.js application. The error occurs when calling connectDB() in server.js. Here's the error message from the Command Prompt:

TypeError: connectDB is not a function
    at Object.<anonymous> (C:\Users\rodri\flutter_auth\server.js:9:1)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Code:

Below are the relevant parts of my code:

server.js

const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const connectDB = require('./config/db');
const passport = require('passport');
const bodyParser = require('body-parser');

connectDB();

const app = express();

if (process.env.NODE_ENV === 'development') {
    app.use(morgan('dev'));
}

const PORT = process.env.PORT || 3000;

app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));

db.js

const mongoose = require('mongoose');
const dbConfig = require('./dbconfig');

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

module.export = connectDB; 


Solution

  • Please change this piece of this code and it should work just fine

    module.exports = connectDB;