I have been experiencing this for a while and I have not really been able to figure out the reason or cause of the error I am experiencing. I do often get the below error message when I am connecting to my DB for the first time. At times it is due to mongoDB server not running. Some other time, even when it is running, the connection still fails.
Has anyone experienced this in the past? How did you resolve it?
Below is the error message I am getting and my mongoDB connection file.
> [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:wwwxPaynode_modulesmongooselibconnection.js:897:11)
at NativeConnection.openUri (C:wwwxPaynode_modulesmongooselibconnection.js:848:11)
at async connectDB (C:wwwxPaybackendconfigdbConn.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
Here is my DB connection file
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;
4
You can try this singleton pattern connect:
connect.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
And use in file app.js
const express = require('express')
const app = express()
// dbs
require('./dbs/connect.mongodb')
module.exports = app
Then, run in 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!`)
})
})
I usually this connect config and compatite all mongodb version I had used
Thắng Huỳnh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.