2 / 2
May 2024

Hi i am facing the same issue

const express = require(“express”);
const dotenv = require(“dotenv”);
const { MongoClient } = require(“mongodb”);
const cors = require(‘cors’);

const bodyParser = require(‘body-parser’);

const app = express();

app.use(express.json())

app.use(cors());

dotenv.config({ path: ‘./config.env’ });
app.use(bodyParser.json());

const PORT = process.env.PORT || 5050;

const userRoutes = require(“./routes/userroutes”)

const mongoURI = process.env.MONGO_URI || “”;

MongoClient.connect(mongoURI)
.then((client) => {
console.log(“MongoDB connected successfully”);

})
.catch((error) => {
console.error(“Error connecting to MongoDB:”, error);
process.exit(1);
});

app.use(“/users”,userRoutes)

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

//userroutes.js

const express = require(“express”)

const router = express.Router()

const UserModel = require(“…/models/User”)

router.post(‘/register’,async(req,res) =>{
try{
console.log(req.body)
const{name,email,password} = req.body

const user = new UserModel({ name, email, password }) await user.save() res.status(201).json(user) } catch(error){ console.log("Error:",error) res.status(500).json({message:error.message}) }

})

module.exports = router

//User.js

const mongoose = require(“mongoose”)

const UserSchema = new mongoose.Schema({
name:{
type:String,
required:true
},

email:{ type:String, required:true }, password:{ type:String, required:true }

})

const UserModel =mongoose.model(“users”,UserSchema)
module.exports = UserModel;

//Signup.js
const handleSubmit = (e) => {
e.preventDefault();

console.log({ name, email, password }); axios .post("http://localhost:5000/users/register", { name, email, password }) .then((result) => console.log(result)) .catch((err) => console.log(err));

};

  1. Mongodb is connecting Successfully
    2.User has all the privellages
    3.It is recieving data from client i.e(Signup)
    4.I tested with mongoshell also it is working with mongoshell and inserting data in db with the same connection String

Hi Jonia,

From the above code, I noticed that you are connecting to mongoDB using MongoClient but you are making requests to mongoDB using mongoose. This is the reason due to which at the time of startup you app is able to connect to mongoDB but when an API call is made then it throws timed out error because then you have not configured your mongoose to connect to the mongoDB.

Here is a sample snippet of how you can connect your mongoose to MongoDB

mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected successfully via Mongoose')) .catch(err => { console.error('Error connecting to MongoDB:', err); process.exit(1); });