You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中使用Mongoose连接MongoDB报错:connect不是函数

解决Next.js中Mongoose连接MongoDB的TypeError问题

在Next.js应用中使用Mongoose连接MongoDB时触发以下错误:

Uncaught (in promise) TypeError: mongoose__WEBPACK_IMPORTED_MODULE_0___default(...).connect is not a function
at mongoDBConnection

相关代码

app/new/FileUpload.tsx

import mongoDBConnection from "../lib/mongoDb";

useEffect(()=> mongoDBConnection()),[]}

app/lib/mongoDB.ts

import mongoose from "mongoose";

const mongoDBConnection = async () =>
await mongoose.connect(process.env.MONGO_URL as string);

export default mongoDBConnection;

next.config.js

/** @type {import('next').NextConfig} */
 const nextConfig = {
 webpack: (config) => {
 config.experiments = { ...config.experiments, topLevelAwait: true };

 return config;
},
 reactStrictMode: true,
 experimental: {
 serverActions: true,
 appDir: true,
 serverComponentsExternalPackages: ["mongoose"],
 },
 images: {
  domains: ["fakestoreapi.com", "firebasestorage.googleapis.com"],
 },
};

module.exports = nextConfig;

解决方案

核心问题

你在客户端组件(FileUpload.tsx使用了useEffect,属于客户端组件)中调用了Mongoose的连接方法,而Mongoose是专为Node.js服务器环境设计的,无法在浏览器端运行,这是错误的根本原因。

具体修复步骤

  1. 将数据库操作移到服务器端执行
    改用Next.js的Server Actions来处理数据库连接和操作:

    • 修改FileUpload.tsx:
      'use client';
      import { initDBConnection } from '../actions/dbActions';
      
      useEffect(() => {
        initDBConnection();
      }, []);
      
    • 创建服务器动作文件app/actions/dbActions.ts:
      'use server';
      import mongoDBConnection from '../lib/mongoDB';
      
      export async function initDBConnection() {
        await mongoDBConnection();
        // 在这里添加你的数据库业务逻辑
      }
      
  2. 优化数据库连接逻辑(避免重复连接)
    修改app/lib/mongoDB.ts,添加单例模式防止重复建立连接:

    import mongoose from "mongoose";
    
    let isConnected = false;
    
    const mongoDBConnection = async () => {
      if (isConnected) {
        console.log('已连接MongoDB,无需重复连接');
        return;
      }
      try {
        await mongoose.connect(process.env.MONGO_URL as string);
        isConnected = true;
        console.log('MongoDB连接成功');
      } catch (error) {
        console.error('MongoDB连接失败:', error);
        throw new Error('无法连接到MongoDB');
      }
    };
    
    export default mongoDBConnection;
    
  3. 确认配置有效性
    你的next.config.js中serverComponentsExternalPackages: ["mongoose"]配置正确,保持不变即可,它会确保Mongoose仅在服务器端打包加载。

  4. 检查Mongoose版本
    确保使用的Mongoose版本适配Next.js App Router,推荐升级到最新稳定版(执行npm update mongoose或yarn upgrade mongoose)。

内容的提问来源于stack exchange,提问作者Captai-N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 19:17:29