I’m using mongoDB atlas for my MERN chat app, and getting the following error:
MongooseError: Operation `users.findOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (/Users/thakur/Desktop/web/react_app/chat-app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:185:23)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512:7)
I tried increasing the server timeout but it didn’t help.
indes.js
const express = require('express');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const User = require('../Models/userModel');
const userRoutes = require('../Routes/userRoutes');
const app = express();
dotenv.config();
app.use(express.json());
mongoose.set('debug', true);
const connectDb = async () => {
try {
const connect = await mongoose.connect(process.env.MONGO_URL,{
serverSelectionTimeoutMS: 30000, // 30 seconds
socketTimeoutMS: 45000 // 45 seconds
});
console.log("Server is connected to the database");
} catch (err) {
console.log("Server is not connected to the database", err.message);
}
};
connectDb();
app.get("/", (req, res) => {
res.send('Api is running on port');
});
app.use("/user", userRoutes);
const PORT = process.env.PORT
app.listen(PORT, console.log('Server is running on port 5050'));
userController.js
const express = require('express');
const asyncHandler = require('express-async-handler');
const UserModel = require('../Models/userModel');
const loginController = () => {};
const registerController = asyncHandler(async (req, res) => {
const { name, email, password } = req.body;
// Check for all fields
if (!name || !email || !password) {
return res.status(400).json({ message: 'All fields are required' });
}
// Pre-existing user
const userExist = await UserModel.findOne({ email });
if (userExist) {
return res.status(400).json({ message: 'User already exists' });
}
// Username already taken
const userNameExist = await UserModel.findOne({ name });
if (userNameExist) {
return res.status(400).json({ message: 'Username already exists' });
}
// Create an entry in database for the user
const user = await UserModel.create({ name, email, password });
res.status(201).json(user);
});
module.exports = { loginController, registerController };
New contributor
Aman Pratap Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1