troychroi
troychroi

Reputation: 49

MongoDB Connection Timing Out

I just downloaded Compass to be able to see my database. npm start goes through but the connection times out. I use curl to keep it open. Once everything is running smoothly, I try to connect on Compass and it says the connection is closed.

Here is what I have in my db.js

mongo.connect('mongodb://localhost:3000/Loc8r', {server: {socketOptions: {keepAlive: 3000}}});

Upvotes: 0

Views: 1452

Answers (2)

Nikhil Jivankar
Nikhil Jivankar

Reputation: 72

try to use this code in your db.js file

const { MongoClient } = require('mongodb');

const uri = 'mongodb://localhost:27017/Loc8r';

const client = new MongoClient(uri, { keepAlive: 3000 });

async function connectToMongo() {
  try {
    await client.connect();
    console.log('Connected to MongoDB successfully');
  } catch (err) {
    console.error('Error connecting to MongoDB:', err);
  } finally {
    client.close();
  }
}

connectToMongo();

Upvotes: 0

Alistair
Alistair

Reputation: 641

If you are using default settings, mongod is probably running on port 27017 so you can use mongo.connect('mongodb://localhost/Loc8r').

Upvotes: 0

Related Questions