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

React应用编译成功但报Uncaught TypeError: mongoose.connect不是函数

问题:React应用编译成功但浏览器控制台报错Uncaught TypeError: mongoose.connect is not a function

错误详情

Uncaught TypeError: mongoose.connect is not a function
    at ./src/db/db.js (db.js:3:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./src/db/notes.js (notes.js:1:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./src/components/notecard-list/NoteList.js (MenuBar.js:19:1)
    at options.factory (react refresh:6:1)

报错文件db.js代码

const mongoose = require('mongoose');

mongoose.connect('<my connection string>', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// Handle database connection events
const db = mongoose.connection;

db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
  console.log('Connected to MongoDB');
});

const noteSchema = new mongoose.Schema({
  address: String,
  title: String,
  content: String,
  citation: String,
});

module.exports = mongoose.model('Note', noteSchema);

已尝试的操作

  • 重新安装mongoose,确认package.json中已正确列出
  • 在db.js中使用const mongoose = require('mongoose');导入包
  • 两次删除并重新安装node_modules和package-lock.json
  • 确认MongoDB连接字符串正确(通过MongoDB Compass验证)

解决方案

核心问题:Mongoose是Node.js后端专属库,完全无法在浏览器环境运行——它依赖Node.js的文件系统、底层网络等仅后端支持的API,同时直接在前端暴露MongoDB连接字符串会导致数据库权限泄露,属于严重安全问题。

正确的解决思路是拆分前后端,通过后端接口操作数据库:

1. 搭建后端服务(以Express为例)

  • 新建后端项目,安装依赖:npm init -y && npm install express mongoose cors
  • 编写后端核心代码(如server.js):
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());

// 连接MongoDB(仅在后端执行)
mongoose.connect('<你的MongoDB连接字符串>', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB连接错误:'));
db.once('open', () => console.log('已连接MongoDB'));

// 定义Note模型
const noteSchema = new mongoose.Schema({
  address: String,
  title: String,
  content: String,
  citation: String,
});
const Note = mongoose.model('Note', noteSchema);

// 编写获取所有笔记的接口
app.get('/api/notes', async (req, res) => {
  const notes = await Note.find();
  res.json(notes);
});

// 启动后端服务
const PORT = 5000;
app.listen(PORT, () => console.log(`后端服务运行在http://localhost:${PORT}`));

2. 修改React前端代码

删除前端项目中src/db目录及相关代码,在NoteList.js中通过接口获取数据:

import { useState, useEffect } from 'react';

function NoteList() {
  const [notes, setNotes] = useState([]);

  useEffect(() => {
    // 调用后端接口获取数据
    fetch('http://localhost:5000/api/notes')
      .then(res => res.json())
      .then(data => setNotes(data))
      .catch(err => console.error('获取笔记失败:', err));
  }, []);

  return (
    <div className="note-list">
      {notes.map(note => (
        <div key={note._id} className="note-card">
          <h3>{note.title}</h3>
          <p>{note.content}</p>
        </div>
      ))}
    </div>
  );
}

export default NoteList;

3. 启动服务

  • 先启动后端:node server.js
  • 再启动React前端:npm start

内容的提问来源于stack exchange,提问作者Tery Gasmen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 19:49:58