Sometimes my DB Connection fails (MongoDB Atlas). Once I re-deployed the application it's working. It's happening frequently. Any specific reasons or suggestions to solve this issue?
Everything is running fine locally, but when deploying, my routes work but very inconsistently.
I also see an error message in the logs like this:
2022-11-28 12:59:51.185: [ERROR] Process timed out after 30 seconds.
My server.js
const path = require('path')
const express = require('express')
const colors = require('colors')
const dotenv = require('dotenv').config()
const { errorHandler } = require('./middleware/errorMiddleware')
const connectDB = require('./config/db')
const port = process.env.PORT || 5000
connectDB()
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use('/api/items', require('./routes/itemRoutes'))
app.use('/api/users', require('./routes/userRoutes'))
//To test if backend deployment worked
app.get('/test', (req, res) => { res.send('Hello! Express server is running!')})
app.use(errorHandler)
const port = process.env.PORT || 5000
app.listen(port, () => console.log(`Server listening on port ${port}`))
db.js where the connectDB
function is:
const mongoose = require('mongoose');
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI);
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline);
} catch (error) {
console.log(error);
process.exit(1);
}
};
module.exports = connectDB;
This works on local but does not work when deploying on cyclic.sh
CodePudding user response:
This is happening because you begin to listen to inbound requests before the MongoDB connection completes its connect
call.
Reading your code I think what is happening is the db starts to get initialized, before the listen call is made the server.js file completes running and ... boom, nothing works.
The pattern of listening to the server port inside of the DB connection call back is to ensure that the DB is connected before express starts listening.
You almost have it. Here is an example: https://docs.cyclic.sh/how-to/using-mongo-db#connection-example-with-expressjs This this at the bottom of your server.js (and don’t call connectDB() higher up)
connectDB().then(() => {
console.log("db connected");
app.listen(port, () => {
console.log("listening for requests");
})
})