Mongoose Error: Buffering timed out after 10000ms

50 Views Asked by At

I want to connect to Mongodb with Thunder client extension in Vs code.

Here's what i have got so far, but now I'm getting an error while connecting the app gets crashed.

const mongoose = require('mongoose');

const mongoURI = "mongodb+srv://****:****@cluster0.jswzjap.mongodb.net"

const connectToMongo = ()=>{
    mongoose.connect(mongoURI, ()=>{
        console.log("Connected to Mongo Successfully");
    })
}

module.exports = connectToMongo;

This is the code for the connection string

D:\I NOTE2\inote3\backend>nodemon ./index.js
[nodemon] 3.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node ./index.js`
Example app listening on port http://localhost:3000
{ name: 'xyz', email: '[email protected]', password: '4567' }
D:\I NOTE2\inote3\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186
          const err = new MongooseError(message);
                      ^

MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (D:\I NOTE2\inote3\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:186:23)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)

Node.js v18.17.1
[nodemon] app crashed - waiting for file changes before starting...

This is the error I'm getting.

1

There are 1 best solutions below

0
jQueeny On

Change your db.js file to an async function:

const mongoose = require('mongoose');

const mongoURI = "mongodb+srv://****:****@cluster0.jswzjap.mongodb.net"

const connectToMongo = async ()=>{
   try {
      // await the connection
      const con = await mongoose.connect(mongoURI);
      console.log(`Connected to mongodb: ${con.connection.host}`);
   } catch (error) {
      throw error;
   }
}

module.exports = connectToMongo;

Then inside your index.js you need to call the function. Just importing it using require isn't enough:

const connectToMongo = require('./db'); 
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json()) // for parsing application/json 

// Now you need to call connectToMongo function
connectToMongo().then(()=> {
   console.log('Connected to db');
}).catch(e => {
   console.log('Error Connecting to db: ', e);
})
  
// Available routes 
app.use('/api/auth', require('./routes/auth'));
app.use('/api/notes',require('./routes/notes'));
app.get('/', (req,res)=>{   res.send("hoo") });
app.listen(port, () => {   
   console.log(`Example app listening on port http://localhost:${port}`) 
});