Connecting to a remote mongoDB server

Viewed 16536

I have a remote machine which I connect to using SSH, I installed mongoDB on it, and I wish to use it remotely, how do I connect to it using nodejs and mongoDB compass? the localhost is the IP ?

const db = "mongodb://what do I write here?";
const connectDB = async () => {
  try {
    await mongoose.connect(db, { useNewUrlParser: true, useCreateIndex: true });
    console.log("MongoDB Connected...");
  } catch (err) {
    console.error(err.message);
    process.exit(1);
  }
};
connectDB();
5 Answers

Short answer

Login to your machine, open mongodb configuration file located at /etc/mongod.conf and change the bindIp field to your machine ip address (it is the same ip address which you are using to ssh to your machine), after that restart mongodb server.


Detailed answer

  • Open /etc/mongod.conf file using any of the editor, if you are running a desktop version then you can make use of gedit utility tool

      sudo gedit /etc/mongod.conf
    

If you are running a server version, then you can make use of vi editor command

    sudo vi /etc/mongod.conf
  • The file should contain the following kind of content:

      systemLog:
          destination: file
          path: "/var/log/mongodb/mongod.log"
          logAppend: true
      storage:
          journal:
              enabled: true
      processManagement:
          fork: true
      net:
          bindIp: 127.0.0.1  // enter your ip address here
          port: 27017
      setParameter:
          enableLocalhostAuthBypass: false
    
  • Once you change the bindIp, then you have to restart the mongodb, using the following command

      sudo service mongod restart
    
  • Now you'll be able to connect to the mongodb server, with the same ip address which you are using to ssh to your system.

      mongoose.connect('mongodb://<machine_ip_address>:27017/<database_name>')
    
mongoose.connect('mongodb://username:password@host:port/database')

Now for the host, is there any hostname or IP you could use?

Try this one:

mongoose.connect("mongodb://localhost/<database-name>", { useNewUrlParser: true });
const db = mongoose.connection
db.on('error', (error) => console.error(error));
db.once('open', () => console.log('Connected to Database'));

Make sure to run MongoDB

mongod --config /usr/local/etc/mongod.conf

If you are using MongoDb Compass

  1. Open 27017 port in Inbound of your Server
  2. Form a link just like mongodb://11.11.111.11 in case you are not going to use auth
  3. Click Connect

Basicly the link is mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

More information here

Related