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

Node.js中signup.js连接MongoDB失败:useCreateIndex选项不支持

MongoDB连接失败问题解决

问题场景

在尝试将MongoDB通过signup.js连接时出现连接失败,替换catch中的日志输出后,得到错误信息:

MongoParseError: option usecreateindex is not supported

相关代码如下:

signup.js

const express = require('express')
const app = express()
require("./db/mydb");

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(4000, () => {
  console.log(`App listening on port 4000`)
})

mydb.js(原错误代码)

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/mydata",{
    useNewUrlParser:true,
    useUnifiedTopology:true,
    useCreateIndex:true
}).then(()=>{
    console.log("connection successful")
}).catch((e)=>{
    console.log("Not connected")
})

错误原因

useCreateIndex是Mongoose旧版本的配置项,新版本中该选项已被移除,且Mongoose会自动处理索引创建,手动配置该选项会触发解析错误。

解决方法

移除连接配置中的useCreateIndex:true即可。修改后的mydb.js代码如下:

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/mydata",{
    useNewUrlParser:true,
    useUnifiedTopology:true
}).then(()=>{
    console.log("connection successful")
}).catch((e)=>{
    console.log(e)
})

修改后重新运行代码,即可正常建立MongoDB连接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:35:29