解决了。问答:MongoDB MongoNetworkError:无法连接到服务器。服务器是远程服务器

时间:2019-07-24 15:59:21

标签: node.js mongodb mongoose

猫鼬连接到MongoDB失败。但是mongo命令行可以连接到MongoDB。

代码:

var mongoose = require('mongoose');

mongoose.connect('mongodb://192.168.92.131/test', {useNewUrlParser: true});

结果:

    (node:6559) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [192.168.92.131:27017] on first connect [Error: 

    connect EHOSTDOWN 192.168.92.131:27017 - Local (192.168.92.1:60222)

    at internalConnect (net.js:835:16)

    at defaultTriggerAsyncIdScope (internal/async_hooks.js:301:12)

    at net.js:926:9

    at processTicksAndRejections 

(内部/进程/task_queues.js:75:11){

    name: 'MongoNetworkError', errorLabels: [Array],

    [Symbol(mongoErrorContextSymbol)]: {}

我的MongoDB安装在运行Ubuntu OS的虚拟机中。我搜索了一个解决方案,但是找不到一个干净的解决方案。

我找到了一个可行的解决方案来分享:

故障排除过程

  1. 运行mongo命令行。连接正常。

  2. 默认情况下,MongoDB没有访问控制(用户/密码)。这样我的代码就可以了。

  3. IP问题? Mongodb不在192.168.92.131上启动

Google:使用外部IP启动mongodb 找到了解决方案:https://www.shellhacks.com/mongodb-allow-remote-access/

ether @ ubuntu_ether:〜$ sudo nano /etc/mongod.conf

无外部IP地址。因此,在mongod.conf中添加IP地址

…....

    enabled: true

#  engine:

#  mmapv1:

#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1, 192.168.92.131

ether@ubuntu_ether:~$ sudo service mongod restart

再次运行:     var mongoose = require('mongoose');     mongoose.connect('mongodb://192.168.92.131/test',{useNewUrlParser:true});

好!

0 个答案:

没有答案