How to use mongo/mongoose to connect to a remote database

Issue

I have a node js app in IP ex: 111.111.111.23:3000 I want to connect from my local express/node app script to my remote mongodb database. the database is running in the IP mention above but for some reason all i can do is connect to my local mongodb databse.

if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });

    mongoose.connect('mongodb://localhost/test');
}

the code above is in my app.js and it works, but what I want to do is something like this.

if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });

    mongoose.connect('mongodb:111.111.111.23:27017/test');
}

I tried adding the ip with and without the port but it fails.

My question is how do I connect to my remote database from my local machine ?

it case this help. The remote server is running ubuntu server 14.04 and I installed mongodb using this guide: https://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

I get the following error:

Error: connect ECONNREFUSED 111.111.111.23:27017

Solution

The mongoose connection format is:

mongoose.connect('mongodb://username:[email protected]:port/database')

if you don’t have username and password, just execute:

mongoose.connect('mongodb://host:port/database');

Source: http://mongoosejs.com/docs/connections.html

You could also try to connect using the mongo client and see if it works..

$ mongo 111.111.111.23:27017

Also, but not likely, make sure your mongod service is up.

$ sudo service mongod start

Finnaly, make sure your firewall is down or open the port using:

$ iptables -A INPUT -p tcp --dport 27017 -j ACCEPT

Answered By – rcmgleite

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published