连接到远程 mongoDB 服务器 [英] Connecting to a remote mongoDB server

查看:102
本文介绍了连接到远程 mongoDB 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台远程机器,我使用 SSH 连接到它,我在它上面安装了 mongoDB,我想远程使用它,我如何使用 nodejs 和 mongoDB 指南针连接到它?本地主机是 IP 吗?

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

推荐答案

简短回答

登录您的机器,打开位于 /etc/mongod.conf 的 mongodb 配置文件并将 bindIp 字段更改为您的机器 ip 地址(它是相同的 ipssh 到您的机器的地址),然后重新启动 mongodb 服务器.

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.

  • 使用任何编辑器打开 /etc/mongod.conf 文件,如果您运行的是桌面版本,则可以使用 gedit 实用工具

  • 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

如果您运行的是服务器版本,那么您可以使用 vi 编辑器 命令

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
      

    • 一旦你改变了bindIp,那么你必须重新启动mongodb,使用以下命令

    • Once you change the bindIp, then you have to restart the mongodb, using the following command

        sudo service mongod restart
      

    • 现在您可以连接到 mongodb 服务器,使用的 IP 地址与您用于 ssh 到您的系统的 IP 地址相同.

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

    • 这篇关于连接到远程 mongoDB 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆