UnhandledPromiseRejectionWarning: MongoNetworkError: 首次连接时无法连接到服务器 \[localhost:27017\] \[MongoNetworkError

新手上路,请多包涵

我尝试运行以下命令:

 node index.js

但是,我从我的终端得到以下信息:

     success connection to port 3000
(node:16767) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError
: connect ECONNREFUSED 127.0.0.1:27017]
    at Pool.<anonymous> (/Users/hatchery/Documents/nodejs/fxexpress/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js:503:11
)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at Connection.<anonymous> (/Users/hatchery/Documents/nodejs/fxexpress/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:326:12)
    at Object.onceWrapper (events.js:317:30)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at Socket.<anonymous> (/Users/hatchery/Documents/nodejs/fxexpress/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:245:50)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
(node:16767) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:16767) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我不确定为什么会收到此错误。谁能建议该怎么做?

原文由 ApplePie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 418
2 个回答

如果您使用的是 mongoDB.Atlas,请转到网络访问并设置白名单条目:0.0.0.0/0。 在此处输入图像描述

在此处输入图像描述

重新运行您的命令。

原文由 Skitty 发布,翻译遵循 CC BY-SA 4.0 许可协议

虽然上述解决方案可能有效,但最好了解如何调试以及错误的内容。

你得到了 UnhandledPromiseRejectionWarning ,因为在你的代码中,你不能处理连接到 MongoDB 的承诺拒绝情况。

接下来,节点服务器无法连接到mongodb。这可能是由于几个原因。 @Sayegh 提到的一个简单案例,服务器本身没有运行。可能是其他原因,如端口错误等,服务器不接受传入连接等。

如何调试。第一步是确定进程是否正在运行。一种简单的方法是运行此命令 ps aux | grep mongo 以文本形式列出所有用户的所有进程。如果这是真的但仍然无法连接,请查找端口。如果仍然无法连接,请检查服务器是否接受传入连接并从那里获取连接。

原文由 AbhinavD 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题