如何解决Node.js中出现的“TypeError: connectDB is not a function”错误?
Hey there! Let's get this sorted out—this is a super common typo that trips up a lot of developers when working with Node.js modules.
The Problem Breakdown
You're getting this error when calling connectDB() in your server.js:
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
Looking at your code, the issue is hiding in your db.js file. Here's the relevant code for context:
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(); // This line throws the error 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); } }; // ❌ This is the mistake! module.export = connectDB;
Why This Happens
Node.js uses module.exports (notice the s at the end) to export values from a module. You wrote module.export (missing the s), which means you're not actually exporting your connectDB function. Instead, when you require('./config/db') in server.js, you're getting the default empty object instead of your function—hence the "not a function" error.
The Fix
Simply correct the typo in db.js by adding the missing s:
// ✅ Correct export syntax module.exports = connectDB;
Save the file, restart your server, and your Mongoose connection should work as expected!
内容的提问来源于stack exchange,提问作者pomoworko.com

