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

MongoDB连接失败问题求助:附终端日志与index.js代码

解决Mongoose连接MongoDB的两个问题:连接失败与strictQuery弃用警告

问题现象

  • 服务器成功在5000端口启动,但MongoDB连接失败,终端输出db error
  • 同时出现Mongoose的strictQuery弃用警告

终端日志

[nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
(node:16036) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)
server is running on 5000
db error

原index.js代码

const express = require('express');

const app = express();

var mongoUrl = "mongodb://localhost:27017/TestDB"
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/TestDB", { useNewUrlParser: true, useUnifiedTopology: true }, (err) => {
    if (!err) console.log('db connected');
    else console.log('db error');
})

app.listen(5000, () => {
    console.log('server is running on 5000');
});

解决方案

1. 消除strictQuery弃用警告

在引入mongoose后,添加配置语句适配Mongoose 7的默认行为:

const mongoose = require('mongoose');
// 添加这行代码适配未来版本
mongoose.set('strictQuery', false);

若需强制保持旧行为(不推荐),可设为true,但建议用false提前适配后续版本迭代。

2. 排查并解决MongoDB连接失败问题

  • 检查MongoDB服务状态:确保本地MongoDB服务已启动
    • Windows:打开服务管理器,找到MongoDB服务并启动
    • Mac:执行brew services start mongodb-community(Homebrew安装场景)
    • Linux:执行sudo systemctl start mongod
  • 优化错误提示:修改连接回调,打印具体错误信息,精准定位问题:
    mongoose.connect("mongodb://localhost:27017/TestDB", { useNewUrlParser: true, useUnifiedTopology: true }, (err) => {
        if (!err) console.log('db connected');
        // 打印具体错误内容
        else console.log('db error:', err);
    })
    
  • 验证连接字符串有效性:确认localhost对应MongoDB服务地址、端口27017未被占用、TestDB数据库具备创建/访问权限

修改后的完整代码示例

const express = require('express');
const app = express();

const mongoose = require('mongoose');
// 消除strictQuery弃用警告
mongoose.set('strictQuery', false);

const mongoUrl = "mongodb://localhost:27017/TestDB";
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true }, (err) => {
    if (!err) console.log('db connected');
    else console.log('db error:', err);
})

app.listen(5000, () => {
    console.log('server is running on 5000');
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:41:28