Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to a remote mongoDB server

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();
like image 478
Alexander Avatar asked Oct 10 '19 12:10

Alexander


People also ask

How do I access MongoDB from another computer?

To connect to MongoDB from a different machine, you must open port 27017 for remote access. Refer to the FAQ for more information on this. IMPORTANT: By default, the database port for the nodes in this solution cannot be accessed over a public IP address.

How do I connect to a MongoDB Community server?

To connect to your local MongoDB, you set Hostname to localhost and Port to 27017 . These values are the default for all local MongoDB connections (unless you changed them). Press connect, and you should see the databases in your local MongoDB.


2 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>')
    
like image 139
Prashant Pokhriyal Avatar answered Nov 15 '22 05:11

Prashant Pokhriyal


mongoose.connect('mongodb://username:password@host:port/database')

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

like image 24
Horatiu Jeflea Avatar answered Nov 15 '22 05:11

Horatiu Jeflea