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

如何解决Mongoose中fruits.insertOne()缓冲超时的MongooseError

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

你的问题核心是数据库连接还没建立就执行了文档保存操作。main()是异步函数,执行时会先发起连接请求,然后直接跳到后面执行fruit.save()和person.save(),这时候Mongoose还没连上MongoDB,只能把这些操作放进缓冲队列,等超过10秒还没连上就抛出超时错误。

修复代码

把所有模型定义、文档创建和保存的逻辑都移到main()函数内部,确保在连接成功后再执行:

//require the Mongoose package (after running >npm i mongoose in Hyper to install it)
const mongoose = require('mongoose');

//connect to MongoDB by specifying port to access MongoDB server
main().catch(err => console.log(err));

async function main() {
  // 加上连接选项,适配新版本MongoDB驱动
  await mongoose.connect('mongodb://localhost:27017/FruitsDB', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  });
  console.log("数据库连接成功");

  //create a SCHEMA that sets out the fields each document will have and their datatypes
  const fruitSchema = new mongoose.Schema ({
      name: String,
      rating: Number,
      review: String
  })
  
  //create a MODEL
  const Fruit = mongoose.model("Fruit", fruitSchema)
  
  //create a DOCUMENT
  const fruit = new Fruit ({
      name: "Apple",
      rating: 7,
      review: "Great!"
  })
  
  //save the document
  await fruit.save()
  console.log("水果文档保存成功");

  //**CHALLENGE: Set up a people database with one document and two fields**//
  //create a SCHEMA
  const personSchema = new mongoose.Schema({
    name: String,
    age: Number,
  });
  
  //create a MODEL
  const Person = mongoose.model('Person', personSchema);
  
  //create a DOCUMENT
  const person = new Person({
    name: "John",
    age: 37
  });
  
  //Save it
  await person.save();
  console.log("人物文档保存成功");
}

额外排查点

  • 确认本地MongoDB服务是否正在运行:打开终端执行mongod,如果提示找不到命令,可能需要把MongoDB的bin目录加到系统环境变量里
  • 检查连接字符串:确保localhost:27017是正确的MongoDB服务地址和端口,FruitsDB是你要创建的数据库名
  • 如果是新版本Mongoose(6.x及以上),连接选项useNewUrlParser和useUnifiedTopology已经默认启用,不加也可以,但加上能兼容旧版本驱动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:25:17