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();
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With