Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 333
Millenial2020 Avatar asked Nov 09 '15 16:11

Millenial2020


1 Answers

The mongoose connection format is:

mongoose.connect('mongodb://username:password@host: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
like image 172
rcmgleite Avatar answered Sep 20 '22 06:09

rcmgleite