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

Mongoose连接MongoDB遇DeprecationWarning及insertOne超时问题求助

问题描述

我通过app.js使用Mongoose创建名为Fruits的数据库并连接MongoDB,代码如下:

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true});

mongoose.set('strictQuery', false);

const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

const fruit = new Fruit({
    name: "Apple",
    rating: 7,
    review: "Taste Good"
});

fruit.save();

运行node app.js时遇到两个问题:

  1. DeprecationWarning:即使设置mongoose.set('strictQuery', true);,警告仍存在,错误信息:

(node:15848) [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)

  1. fruits.insertOne()超时错误:数据库未更新,错误信息:
D:\Web Development\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:158
          const err = new MongooseError(message);
                      ^

MongooseError: Operation `fruits.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (D:\Web Development\FruitsProject\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:158:23)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)

Node.js v18.12.1

当前数据库列表:

test> show dbs
admin    40.00 KiB
config  108.00 KiB
local    40.00 KiB
shopDB   72.00 KiB
解决方法

1. 修复strictQuery弃用警告

问题出在设置strictQuery的时机——当前代码是在调用mongoose.connect()之后才设置,此时Mongoose已初始化完成,设置不会生效。

正确做法:在调用mongoose.connect()之前先设置strictQuery:

const mongoose = require("mongoose");

// 先设置strictQuery
mongoose.set('strictQuery', false);
// 再连接数据库
mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true});

// 后续代码不变
const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

const fruit = new Fruit({
    name: "Apple",
    rating: 7,
    review: "Taste Good"
});

fruit.save();

设置完成后警告会消失;若需保留严格查询模式,将false改为true即可,同样要放在connect操作之前。

2. 解决insertOne()缓冲超时错误

该错误核心原因是Mongoose未成功连接MongoDB,导致插入操作等待连接超时,可从以下方向排查修复:

检查MongoDB服务状态

  • 打开命令行输入mongod,若提示命令不存在,说明MongoDB未添加到系统环境变量,或服务未启动。
  • Windows用户可通过服务管理器查看MongoDB Server是否运行;Mac/Linux用户可通过brew services list(Homebrew安装场景)或systemctl status mongod检查服务状态。

验证连接字符串正确性

  • 确认MongoDB默认端口27017未修改,若自定义过端口,需同步修改连接字符串中的端口号。
  • 若MongoDB设置了用户名密码,连接字符串需改为:mongodb://username:password@localhost:27017/fruitsDB?authSource=admin

添加连接错误处理与回调

修改连接代码,添加回调或使用async/await,明确连接状态:

mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true})
  .then(() => console.log("数据库连接成功"))
  .catch(err => console.log("数据库连接失败:", err));

通过回调可直接获取连接失败的具体原因,比如权限问题、服务未启动等。

确保插入操作在连接成功后执行

将fruit.save()放在连接成功的回调中,避免连接未完成就执行插入:

mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true})
  .then(() => {
    console.log("数据库连接成功");
    const fruit = new Fruit({
      name: "Apple",
      rating: 7,
      review: "Taste Good"
    });
    return fruit.save();
  })
  .then(() => {
    console.log("数据插入成功");
    // 插入完成后可关闭连接
    mongoose.connection.close();
  })
  .catch(err => console.log(err));

验证结果

修改后重新运行node app.js,若无报错,打开MongoDB shell输入以下命令验证:

use fruitsDB
show collections
db.fruits.find()

此时能看到插入的Apple数据,show dbs列表中也会出现fruitsDB。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:20:32