Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"failed to connect to server" even after mongodb is back up #375

Closed
SamDecrock opened this issue Jun 17, 2019 · 1 comment
Closed

"failed to connect to server" even after mongodb is back up #375

SamDecrock opened this issue Jun 17, 2019 · 1 comment

Comments

@SamDecrock
Copy link

SamDecrock commented Jun 17, 2019

When I start my node.js app WITHOUT MongoDB up and do a db.find I get

failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]

I then try the db.find every 2 seconds, but even when I start up my MongoDB afterwards, I still get

failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]

When I restart my node.js script all works perfect.

I want this to work as there might be a case when MongoDB is not up when I start my Node.js app. Eg when using Docker compose.

@SamDecrock
Copy link
Author

SamDecrock commented Jun 17, 2019

Ok. I fixed my problem by reinitializing the mongojs object when connection fails:

var db = null;

function connectToMongoDb(callback) {
	db = mongojs(mongojsConnectionString); // key to success!

	db.on('error', (err) => {});

	db.users.find({}, (err) => {
		if(err) {
			console.log('Error connecting to db:', err.message);

			setTimeout(() => {
				connectToMongoDb(callback);
			}, 2000);
		}else{
			callback();
		}
	});
}

connectToMongoDb(() => {
	console.log('Connected! Whoohoo!');
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant