Node.js运行Mongoose报错:SyntaxError: Unexpected token '.'
问题排查:Node.js + Mongoose连接MongoDB时出现SyntaxError报错
错误信息
[nodemon] 3.0.2 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,cjs,json [nodemon] starting `node server.js` /home/harithriyadh/prayer-tracker/node_modules/mongoose/node_modules/mongodb/lib/admin.js:62 session: options?.session, ^ SyntaxError: Unexpected token '.' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/modules/cjs/loader.js:963:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) at Module.load (internal/modules/cjs/loader.js:863:32) at Function.Module._load (internal/modules/cjs/loader.js:708:14) at Module.require (internal/modules/cjs/loader.js:887:19) at require (internal/modules/cjs/helpers.js:74:18) at Object.<anonymous> (/home/harithriyadh/prayer-tracker/node_modules/mongoose/node_modules/mongodb/lib/index.js:6:17) at Module._compile (internal/modules/cjs/loader.js:999:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) [nodemon] app crashed - waiting for file changes before starting...
数据库连接代码
const mongoose = require("mongoose"); const dbUrl = "mongodb+srv://username:password@harith.pl58u3c.mongodb.net/?retryWrites=true&w=majority"; const connectionParams = { useNewUrlParser: true, useUnifiedTopology: true, }; mongoose .connect(dbUrl, connectionParams) .then(() => { console.info("Connected to the DB"); }) .catch((e) => { console.log("Error:", e); });
问题原因
报错中的options?.session是ES2020引入的可选链操作符,当前使用的Node.js版本不支持该语法。可选链默认在Node.js 14.0.0及以上版本支持,低于此版本的Node.js会无法识别?.语法,从而抛出SyntaxError。
解决方法
方法1:升级Node.js版本(推荐)
升级到Node.js 14.x及以上版本,即可原生支持可选链语法。如果使用nvm(Node版本管理器),执行以下命令:
# 安装最新的LTS版本(比如18.x) nvm install 18 # 切换到该版本 nvm use 18
也可以直接从Node.js官方渠道下载对应版本的安装包进行更新。
方法2:降级Mongoose依赖
如果无法升级Node.js,可降级Mongoose到适配旧Node版本的5.x系列(Mongoose 6+依赖的MongoDB驱动已使用ES2020特性):
# 卸载现有Mongoose npm uninstall mongoose # 安装5.x稳定版 npm install mongoose@5.13.20
内容的提问来源于stack exchange,提问作者Harith Riyadh
相关产品推荐
相关产品推荐

