我正在尝试从节点应用程序连接到mlab数据库,并且在尝试连接时它只是挂起。即使我的mlab数据库使用其他端口,它也会显示错误中的默认端口27017。

我在其他项目上使用过mlab和mongoose,但从未收到此错误,因此非常困惑。

错误:

{ MongoTimeoutError: Server selection timed out after 30000 ms
    at Timeout.setTimeout [as _onTimeout] (/Users/<user>/playground/mongo-test/node_modules/mongodb/lib/core/sdam/server_selection.js:308:9)
    at ontimeout (timers.js:475:11)
    at tryOnTimeout (timers.js:310:5)
    at Timer.listOnTimeout (timers.js:270:5)
  name: 'MongoTimeoutError',
  reason:
   { Error: getaddrinfo ENOTFOUND <my username> <my username>:27017
    at errnoException (dns.js:50:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
     name: 'MongoNetworkError',
     [Symbol(mongoErrorContextSymbol)]: {} },
  [Symbol(mongoErrorContextSymbol)]: {} }


我的代码:

const express = require('express');
const app = express();
const mongoose = require('mongoose');

const PORT = process.env.PORT || 8000;

mongoose.connect('mongodb://<my username>:<my password>@<theservername>.mlab.com:59577/express-chat-dev', { useNewUrlParser: true, useUnifiedTopology: true }, (err) => {
    console.log('[hello]');
    if (err) {
        console.error(err);
    } else {
        console.log('[mongo connected]');
    }
});

app.listen(PORT, () => {
    console.log(`Express running on port ${PORT}`)
})

最佳答案

因此,我不确定这是否是API更改,但是将我的凭据移动到options对象中解决了我的问题。

const express = require('express');
const app = express();
const mongoose = require('mongoose');

const PORT = process.env.PORT || 8000;

const options = {
  user: <username>,
  pass: <password>,
  useNewUrlParser: true,
  useUnifiedTopology: true
}

mongoose.connect('mongodb://<theservername>.mlab.com:59577/express-chat-dev', options, (err) => {
    console.log('[hello]');
    if (err) {
        console.error(err);
    } else {
        console.log('[mongo connected]');
    }
});

app.listen(PORT, () => {
    console.log(`Express running on port ${PORT}`)
})

关于node.js - Mongoose 将无法连接到Mlab,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59400145/

10-09 20:35