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

如何修复MongoNotConnectedError及Mongoose MongoDB连接异常

问题描述

运行以下代码时遇到MongoDB连接及数据保存的错误:

文件productinit.js

const product = require('../model/product');
const mongoose= require('mongoose');

const connectDB = async () => {
    await mongoose.connect('mongodb://127.0.0.1:27017/orders', {bufferTimeout: null});
    console.log('Connected to MongoDB');
  };
  connectDB();

const products = [
    new product({
        imagePath:"/images/about/a1.png",
        productName: "iphone 8+ ",
        price: 200,
        information:
        { 
        displaySize: 6.5,
        storageCapacity: 64,
        CameraResolution: 16,
        numberOfSIM: "Dual SIM"
        }}),

    new product({
        imagePath:"/images/about/a2.png",
        productName: "iphone 8 ",
        price: 240,
        information:
        { 
            displaySize: 5.5,
            storageCapacity: 64,
            CameraResolution: 16,
            numberOfSIM: "Dual SIM"
        }}),
 
     new product({
         imagePath:"/images/about/a3.png",
         productName: "iphone 7+ ",
         price: 180,
         information:
            { 
                displaySize: 6.1,
                storageCapacity: 64,
                CameraResolution: 15,
                numberOfSIM: "Dl SIM"
        }}),
    
    new product({
        imagePath:"/images/about/a4.png",
        productName: "iphone 7 ",
        price: 180,
        information:
                { 
                    displaySize: 6.1,
                    storageCapacity: 32,
                    CameraResolution: 15,
                    numberOfSIM: "Dl SIM"
        }}),
        
    new product({
            imagePath:"/images/about/a5.png",
            productName: "iphone 7+ ",
            price: 180,
            information:
            { 
                displaySize: 6.1,
                storageCapacity: 64,
                CameraResolution: 15,
                numberOfSIM: "Dl SIM"
        }}),

    new product({
                imagePath:"/images/about/a6.png",
                productName: "iphone 7+ ",
                price: 180,
                information:
                { 
                    displaySize: 6.1,
                    storageCapacity: 64,
                    CameraResolution: 15,
                    numberOfSIM: "Dl SIM"
        }}),
        
]

var done = 0;
mongoose.connect('mongodb://127.0.0.1:27017/orders');

for (var i = 0; i < products.length; i++) {
    console.log(i);
    var doc = products[i].save().then(() => console.log("Product saved")).catch(err => console.log(err));
    console.log(doc);
    done++;
    if (done === products.length) {
        mongoose.disconnect();
    }
}

文件product.js

const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
    imagePath:{type:String, required:true},
    productName:{type:String, required:true},
    price:{type:Number, required:true},
    information:
    {
        required:true,
        type:
        {
            displaySize: Number,
            storageCapacity:Number,
            CameraResolution: Number,
            numberOfSIM: String
        }
    }
});


module.exports=mongoose.model('product',productSchema)

错误信息

使用127.0.0.1连接时:

0
Promise { <pending> }
1
Promise { <pending> }
2
Promise { <pending> }
3
Promise { <pending> }
4
Promise { <pending> }
5
Promise { <pending> }
Connected to MongoDB
MongoNotConnectedError: Client must be connected before running operations
    at executeOperationAsync (C:\courses\node-js\shopping-cart\node_modules\mongodb\lib\operations\execute_operation.js:23:19)
    at C:\courses\node-js\shopping-cart\node_modules\mongodb\lib\operations\execute_operation.js:12:45
    at maybeCallback (C:\courses\node-js\shopping-cart\node_modules\mongodb\lib\utils.js:293:21)
    at executeOperation (C:\courses\node-js\shopping-cart\node_modules\mongodb\lib\operations\execute_operation.js:12:38)
    at Collection.insertOne (C:\courses\node-js\shopping-cart\node_modules\mongodb\lib\collection.js:157:57)
    at NativeCollection.<computed> [as insertOne] (C:\courses\node-js\shopping-cart\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:243:33)
    at Collection.doQueue (C:\courses\node-js\shopping-cart\node_modules\mongoose\lib\collection.js:128:23)
    at C:\courses\node-js\shopping-cart\node_modules\mongoose\lib\collection.js:75:24
    at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
  [Symbol(errorLabels)]: Set(0) {}
}
[重复错误信息省略]

改用localhost连接时:

MongooseError: Operation `products.insertOne()` buffering timed out after 10000ms at Timeout
err = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
解决方案

1. 修复MongoDB连接逻辑,确保连接完成后再执行数据保存

原代码重复调用mongoose.connect,且未等待连接成功就执行save操作,导致连接未就绪时发起数据库操作。修改productinit.js,将所有逻辑包裹在连接成功后的异步流程中:

const product = require('../model/product');
const mongoose = require('mongoose');

const connectDB = async () => {
  try {
    await mongoose.connect('mongodb://127.0.0.1:27017/orders');
    console.log('Connected to MongoDB');
    // 连接成功后执行数据保存
    await saveProducts();
    // 所有数据保存完成后断开连接
    await mongoose.disconnect();
    console.log('Disconnected from MongoDB');
  } catch (err) {
    console.error('MongoDB connection error:', err);
    process.exit(1);
  }
};

const saveProducts = async () => {
  const products = [
    new product({
      imagePath: "/images/about/a1.png",
      productName: "iphone 8+ ",
      price: 200,
      information: {
        displaySize: 6.5,
        storageCapacity: 64,
        CameraResolution: 16,
        numberOfSIM: "Dual SIM"
      }
    }),
    new product({
      imagePath: "/images/about/a2.png",
      productName: "iphone 8 ",
      price: 240,
      information: {
        displaySize: 5.5,
        storageCapacity: 64,
        CameraResolution: 16,
        numberOfSIM: "Dual SIM"
      }
    }),
    new product({
      imagePath: "/images/about/a3.png",
      productName: "iphone 7+ ",
      price: 180,
      information: {
        displaySize: 6.1,
        storageCapacity: 64,
        CameraResolution: 15,
        numberOfSIM: "Dl SIM"
      }
    }),
    new product({
      imagePath: "/images/about/a4.png",
      productName: "iphone 7 ",
      price: 180,
      information: {
        displaySize: 6.1,
        storageCapacity: 32,
        CameraResolution: 15,
        numberOfSIM: "Dl SIM"
      }
    }),
    new product({
      imagePath: "/images/about/a5.png",
      productName: "iphone 7+ ",
      price: 180,
      information: {
        displaySize: 6.1,
        storageCapacity: 64,
        CameraResolution: 15,
        numberOfSIM: "Dl SIM"
      }
    }),
    new product({
      imagePath: "/images/about/a6.png",
      productName: "iphone 7+ ",
      price: 180,
      information: {
        displaySize: 6.1,
        storageCapacity: 64,
        CameraResolution: 15,
        numberOfSIM: "Dl SIM"
      }
    })
  ];

  // 使用Promise.all等待所有保存操作完成
  await Promise.all(products.map(async (prod) => {
    await prod.save();
    console.log(`Product saved: ${prod.productName}`);
  }));
};

connectDB();

2. 修复Schema中嵌套对象的定义

原product.js中information字段的Schema定义格式错误,嵌套对象需要正确声明结构:

const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
  imagePath: { type: String, required: true },
  productName: { type: String, required: true },
  price: { type: Number, required: true },
  information: {
    type: {
      displaySize: Number,
      storageCapacity: Number,
      CameraResolution: Number,
      numberOfSIM: String
    },
    required: true
  }
});

module.exports = mongoose.model('product', productSchema);

3. 解决localhost连接被拒绝的问题

出现connect ECONNREFUSED ::1:27017是因为系统将localhost解析为IPv6地址::1,但MongoDB可能未监听IPv6端口。解决方法:

  • 继续使用127.0.0.1作为连接地址(推荐)
  • 或者修改MongoDB配置,使其监听IPv6地址
  • 也可以在连接选项中添加family: 4强制使用IPv4:
    await mongoose.connect('mongodb://localhost:27017/orders', { family: 4 });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:40:04