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

Node.js使用Mongoose查询MongoDB数据后断开连接报会话过期错误

报错原因
  • 核心问题是数据库连接关闭时机错误:你在find查询的回调函数中先执行了mongoose.connection.close(),再遍历打印水果名称。虽然查询已经返回了结果数据,但Mongoose内部仍需要使用当前会话完成后续收尾操作,提前关闭连接会直接销毁会话,触发MongoExpiredSessionError错误。
  • 你看到终端先打印出4次Apple、1次Kiwi,是因为遍历打印是同步操作,会在连接关闭的异步逻辑生效前执行完成,报错是连接销毁后Mongoose内部未完成的操作触发的。
修复方法

快速修改

直接调整find回调内的代码顺序,先完成所有业务操作(遍历打印),再关闭数据库连接即可:

Fruit.find(function(err, fruits) {
  if (err) {
    console.log(err);
    return mongoose.connection.close();
  }
  // 先遍历打印所有水果名称
  fruits.forEach(function(fruit) {
    console.log(fruit.name);
  });
  // 所有操作完成后再关闭连接
  mongoose.connection.close();
});

更稳妥的异步写法(推荐)

使用async/await语法统一处理异步逻辑,避免回调嵌套,也能更精准控制操作顺序:

const mongoose = require('mongoose');

const fruitSchema = new mongoose.Schema({
  name: String,
  rating: {
    type: Number,
    min: 1,
    max: 10
  },
  review: String
});

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

async function run() {
  // 等待数据库连接成功再执行后续操作
  await mongoose.connect("mongodb://localhost:27017/fruitsDB", {
    useNewUrlParser: true
  });

  // 如果需要将创建的kiwi存入数据库,取消下方两行注释即可
  // const kiwi = new Fruit({ name: "Kiwi", rating: 10, review: "great" });
  // await kiwi.save();

  // 查询所有水果数据
  const fruits = await Fruit.find();
  fruits.forEach(fruit => console.log(fruit.name));

  // 所有操作执行完成后关闭连接
  await mongoose.connection.close();
}

// 捕获全局异步错误
run().catch(err => console.log(err));

补充说明:你查询到4条Apple记录是因为之前多次运行代码时多次插入了Apple数据,如果需要清理重复数据,手动删除集合内的重复记录即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:18:02