大多数情况下与 MongoDB 的连接失败

问题描述 投票:0回答:1

我遇到这种情况已经有一段时间了,但我还没有真正弄清楚我遇到的错误的原因或原因。当我第一次连接到数据库时,我经常收到以下错误消息。有时这是由于 mongoDB 服务器未运行。有时,即使正在运行,连接仍然失败。

过去有人经历过这种情况吗?你是怎么解决的?

下面是我收到的错误消息和我的 mongoDB 连接文件。


> [email protected] backend
> nodemon server.js

[nodemon] 3.1.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node server.js`
Server is running on port 5000
Failed to connect to MongoDB: MongooseServerSelectionError: connection timed out
    at _handleConnectionErrors (C:\www\xPay\node_modules\mongoose\lib\connection.js:897:11)
    at NativeConnection.openUri (C:\www\xPay\node_modules\mongoose\lib\connection.js:848:11)
    at async connectDB (C:\www\xPay\backend\config\dbConn.js:9:5) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined

这是我的数据库连接文件

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    const dbURI = "mongodb://localhost:27017/xPay";

    await mongoose.connect(dbURI);

    const db = mongoose.connection;

    db.on("error", (error) => {
      console.error("MongoDB connection error:", error);
    });

    db.once("open", () => {
      console.log("MongoDB connected successfully");
    });
  } catch (error) {
    console.error("Failed to connect to MongoDB:", error);
    process.exit(1); // Exit the process with failure
  }
};

module.exports = connectDB;
node.js mongodb mongoose
1个回答
0
投票

您可以尝试这种单例模式连接: 连接.mongodb.js

'use strict'

const mongoose = require('mongoose')
const { db: { host, port, name }} = require('../configs/mongodb.config')
const connectString = `mongodb://${host}:${port}/${name}`

console.log(connectString)

class Database {
  constructor() {
    this.connect()
  }

  connect(type = 'mongodb') {
    if(1 === 1) {
      mongoose.set('debug', true)
      mongoose.set('debug', { color: true})
    }

    mongoose.connect(connectString).then((_) => {
      console.log(`Connected to mongodb`)
    }).catch((error) => {
      console.log(`Error connection!`, error)
    })
  }

  static getInstance() {
    if(!Database.instance) {
      Database.instance = new Database()
    }

    return Database.instance
  }
}

const instanceMongodb = Database.getInstance()
module.exports = instanceMongodb

并在文件 app.js 中使用

const express = require('express')

const app = express()

// dbs
require('./dbs/connect.mongodb')

module.exports = app

然后,在server.js中运行

const app = require("./src/app");
const PORT = process.env.PORT || 4000

const server = app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`)
})

process.on('SIGINT', () => {
  server.close(() => {
    console.log(`Server has closed!`)
  })
})

我通常会使用此连接配置并兼容我使用过的所有 mongodb 版本

© www.soinside.com 2019 - 2024. All rights reserved.