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
相关产品推荐
相关产品推荐

