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

App*_*Pie 2 javascript mongodb node.js express handlebars.js

我试图运行以下命令:

node index.js
Run Code Online (Sandbox Code Playgroud)

但是,我从终端获得以下内容:

    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.
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我会收到这个错误.任何人都可以建议做什么?

小智 20

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

在此处输入图片说明

重新运行您的命令。


Abh*_*avD 8

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

你得到了UnhandledPromiseRejectionWarning,因为在你的代码中,你不能处理与MongoDB连接的promise promise案例.

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

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


Say*_*egh 6

不确定你在使用什么系统,但如果你在Linux上,请尝试运行它:

mongo
Run Code Online (Sandbox Code Playgroud)

或者对于macOS:

mongod
Run Code Online (Sandbox Code Playgroud)

并让它在新终端中运行,然后再次尝试运行服务器

  • 你之所以真的曾经做过一次.如果您只是直接关闭终端,则服务器仍将保留在后台,直到您重新启动计算机 (2认同)