导入Mongoose后Node.js服务器崩溃,报语法错误
问题:导入Mongoose后Node.js服务器崩溃抛出语法错误
导入Mongoose后,Node.js服务器立即崩溃,抛出如下语法错误:
/home/kashif/git/edemy/server/node_modules/mongodb/lib/collection.js:74 pkFactory: db.options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY, ^ SyntaxError: Invalid or unexpected token at Module._extensions..js (node:internal/modules/cjs/loader:1309:10) Node.js v20.2.0
未导入Mongoose时服务器运行正常,尝试用Mongoose连接MongoDB数据库,但导入后就触发该错误。相关文件内容如下:
server.js 文件
// setting server using express now import express from "express"; import cors from "cors"; // import fs from "fs"; we dont need the whole file syst instead we can destructure just the readdirSync function import { readdirSync } from "fs"; import morgan from "morgan"; import mongoose from "mongoose"; // import doenv config import dotenv from "dotenv"; dotenv.config(); // create express app const app = express(); // when we execute exrpess that entire express app is available in this variable app // apply middlewares ( code which runs between request and response) app.use(cors()); // cors is a middleware which allows to connect to the server from different domain app.use(express.json()); // express.json() is a middleware which allows to read json data from request body app.use(morgan("dev")); // morgan is a middleware which logs the request details in the console //Routes readdirSync("./routes").map((r) => { //apply as middelware now app.use("/api", require(`./routes/${r}`)); }); const port = process.env.PORT || 8000; // process.env.PORT is used to get the port number from the .env file and if it is not available then it will use 8000 as default port. Process is a global variable in nodejs which allow us to access the environment variables and other process related information // start listening to port app.listen(port, () => { console.log(`server is running on port ${port}`); });
package.json 文件
{ "name": "server", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "nodemon -r esm server.js" }, "author": "", "license": "ISC", "dependencies": { "bcrypt": "^5.1.1", "cors": "^2.8.5", "dotenv": "^16.3.1", "esm": "^3.2.25", "express": "^4.18.2", "jsonwebtoken": "^9.0.1", "mongoose": "^7.5.0", "morgan": "^1.10.0", "nodemon": "^3.0.1" } }
解决方案
1. 替换第三方esm模块加载器为Node.js原生ESM支持
错误根源是第三方esm包与MongoDB依赖中的现代JavaScript语法(可选链?.、空值合并??)不兼容。Node.js v12+已原生支持ESM,无需依赖第三方包:
- 卸载
esm包:npm uninstall esm - 修改
package.json,添加"type": "module"并更新启动脚本:{ "name": "server", "version": "1.0.0", "type": "module", // 新增该行,启用原生ESM "description": "", "main": "index.js", "scripts": { "start": "nodemon server.js" // 移除-r esm参数 }, // 其余依赖项保持不变 } - 修复路由导入逻辑(原生ESM不支持
require,需改用异步import):
修改server.js中的路由代码:import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); // 封装异步启动逻辑 const startServer = async () => { // 遍历路由文件并导入 for (const r of readdirSync(join(__dirname, './routes'))) { const routerModule = await import(`./routes/${r}`); app.use("/api", routerModule.default); } // 启动服务器 app.listen(port, () => { console.log(`server is running on port ${port}`); }); }; startServer();
2. 清理依赖缓存并重新安装
若仍有问题,清理缓存后重新安装依赖:
rm -rf node_modules package-lock.json npm install
3. 验证版本兼容性
Mongoose 7.x要求Node.js版本≥14.20.0/16.13.0/18.0.0/20.0.0,你的Node.js v20.2.0符合要求。如果问题持续,可尝试升级Mongoose到最新兼容版本:
npm install mongoose@latest
内容的提问来源于stack exchange,提问作者Kashif
相关产品推荐
相关产品推荐

