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

Mongoose执行Model.insertMany超时 MongoDB shell不显示新建数据库

报错根因分析
  • 端口填写错误:MongoDB默认服务端口为27017,你的代码中连接字符串误写为27107,导致Mongoose无法连接到MongoDB服务,直接抛出ECONNREFUSED连接拒绝错误
  • 数据库操作时机错误:你没有等待Mongoose与MongoDB完成连接就直接执行insertMany操作,Mongoose会将连接建立前的数据库操作缓存,连接超时后就会抛出缓冲超时报错
  • 数据库显示规则问题:MongoDB默认不会将空数据库计入show dbs的返回结果,只有当库中插入至少一条有效文档后,数据库才会持久化显示
解决步骤
  1. 修正MongoDB连接字符串
    将原连接代码替换为正确端口的版本:
//a) connect to mongoDB
mongoose.connect("mongodb://localhost:27017/todolistDB", {useNewUrlParser: true, useUnifiedTopology: true});
  1. 调整初始化数据插入逻辑,等待连接成功后再执行操作,同时避免重复插入默认数据
    在连接代码后添加连接监听逻辑,将insertMany操作放到连接成功的回调中:
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB连接错误:'));
db.once('open', function() {
  console.log("MongoDB连接成功");
  // 先查询集合是否已有数据,避免每次启动重复插入
  Item.find({}, function(err, foundItems){
    if (err) {
      console.log(err);
    } else if (foundItems.length === 0) {
      Item.insertMany(defaultItems, function(e){
        if (e) {
          console.log(e);
        } else {
          console.log("默认任务插入成功");
        }
      });
    }
  });
});
  1. 修正代码中未定义变量的问题
    你当前根路由渲染时用到的items变量、/work路由用到的workItems变量都没有定义,需要改为从MongoDB查询获取对应数据,以根路由为例:
app.get("/", function(req,res) {
  Item.find({}, function(err, foundItems){
    res.render("list", {
      listTitle: "my daily routine",
      newListItems: foundItems
    });
  });
});
  1. 验证效果
  • 确认mongod服务正常运行,默认监听27017端口
  • 重新执行node app.js启动项目
  • 完成默认数据插入后,在mongo shell执行show dbs即可看到todolistDB数据库

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:09:03