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

导出Mongoose连接至其他文件时遇模块找不到错误求助

解决方案

1. 修正路径大小写问题

你的文件路径存在大小写不一致:

  • Mongoose连接文件路径是 myApp/src/db/mongoose.js
  • Express入口文件路径是 myapp/index.js

Linux/macOS系统对文件名大小写敏感,myApp 和 myapp 会被识别为两个不同目录。请统一文件夹名称(比如都改为myApp),确保入口文件与连接文件处于同一根目录下。

2. 统一ES模块语法,避免混用CommonJS

在 myApp/src/db/mongoose.js 中,将CommonJS导出改为ES模块导出,同时优化连接逻辑(用Promise替代回调,便于捕获错误):

import mongoose from "mongoose";

mongoose.set("strictQuery", true);

// 使用Promise处理连接,支持错误捕获
mongoose.connect("mongodb://localhost:27017/task-manager-api", { useNewUrlParser: true })
  .then(() => console.log("connected to database"))
  .catch(err => console.error("database connection error:", err));

// ES模块标准导出
export default mongoose;

3. 确保项目启用ES模块

在项目根目录的 package.json 中添加 "type": "module",告知Node.js将所有.js文件当作ES模块处理:

{
  "type": "module",
  // 其他项目配置...
}

4. 修正导入路径

在 myApp/index.js 中使用正确的相对路径导入(若index.js在根目录,路径应为./src/db/mongoose或./src/db/mongoose.js):

import express from "express";
import "./src/db/mongoose";

const app = express();
const port = 3000;

app.use(express.json());

app.listen(port, () => {
  console.log("listening on port 3000");
});

额外排查点

  • 确认本地MongoDB服务正在localhost:27017端口运行
  • 检查依赖是否安装完整:执行 npm install express mongoose

内容的提问来源于stack exchange,提问作者Smeet Thakkar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:50:44