Mongodb Atlas Express.js错误:getaddrinfo ENOTFOUND

时间:2019-05-06 09:29:42

标签: mongodb express

我想将我的Express应用程序连接到mongoDb Atlas集群。
我来自伊朗,云数据库已经为我们认可。我使用VPN绕过它以便能够练习。 是我做过编码错误还是由于使用VPN?

错误:

(node:9008) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

connected

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: getaddrinfo ENOTFOUND
is listening...

    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
Emitted 'error' event at:
    at GetAddrInfoReqWrap.doListen [as callback] (net.js:1448:12)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:17)
[nodemon] app crashed - waiting for file changes before starting...

和代码:

database.js
----------------

const mongoDb = require('mongodb');
const MongoClient = mongoDb.MongoClient;

let _db;

const mongoConnect = callback => {
  MongoClient.connect(
    'mongodb+srv://<someUser>:<somePassword>@<someCluster>-zh1eb.mongodb.net/test?retryWrites=true'
  )
    .then(client => {
      console.log('\nconnected\n');
      _db = client.db();
      callback();
    })
    .catch(err => {
      console.log('\nerror\n', err);
      throw err;
    });
};

const getDb = () => {
  if (_db) {
    return _db;
  }
  throw 'NO DATABASE FOUND';
};

exports.mongoConnect = mongoConnect;
exports.getDb = getDb;




app.js
------------

...
const mongoConnect = require('./util/database').mongoConnect;
...

mongoConnect(() => {
  app.listen(3000, '\nis listening...\n');
});

1 个答案:

答案 0 :(得分:0)

我发现了问题所在

mongoConnect(() => {
  app.listen(3000, '\nis listening...\n');
});

实际上应该是

mongoConnect(() => {
  app.listen(3000, () => { console.log('\nis listening...\n');});
});

Silly me ...:)

对于有此类问题的人:
首先检查问题的根源是您的代码还是与MongoDb的连接。
那不是选择“连接您的应用程序”,而是选择“使用Mongodb Compass连接”
如果Mongodb Compass可以连接并显示您的集群,那么您的代码肯定存在问题,特别是。连接的编码方式。