Connecting to a remote mongoDB server

北慕城南 提交于 2020-12-09 09:30:40

问题


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();

回答1:


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>')
    



回答2:


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

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




回答3:


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




回答4:


first try this : mongoose.connect('mongodb://localhost:27017/database')

mongoose.connect('mongodb://<machine_ip_address>:27017/<database_name>')

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]

check https://docs.mongodb.com/manual/reference/connection-string/



来源:https://stackoverflow.com/questions/58323458/connecting-to-a-remote-mongodb-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!