在node.js中连接Mongodb时出现错误CONNREFUSED

wf82jlnq  于 2022-11-22  发布在  Go
关注(0)|答案(2)|浏览(177)

我尝试使用Node.js设置MongoDB,但一直收到以下错误:

Uncaught MongooseServerSelectionError MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at MongooseError (c:\Users\lilpi\mongo\node_modules\mongoose\lib\error\mongooseError.js:7:1)
    at MongooseServerSelectionError (c:\Users\lilpi\mongo\node_modules\mongoose\lib\error\serverSelection.js:26:1)
    at Connection.openUri (c:\Users\lilpi\mongo\node_modules\mongoose\lib\connection.js:824:32)
    at <anonymous> (c:\Users\lilpi\mongo\node_modules\mongoose\lib\index.js:381:10)
    at <anonymous> (c:\Users\lilpi\mongo\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5)
    at promiseOrCallback (c:\Users\lilpi\mongo\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
    at Mongoose._promiseOrCallback (c:\Users\lilpi\mongo\node_modules\mongoose\lib\index.js:1234:10)
    at Mongoose.connect (c:\Users\lilpi\mongo\node_modules\mongoose\lib\index.js:380:20)
    at <anonymous> (c:\Users\lilpi\mongo\app.js:3:10)
    at Module._compile (internal/modules/cjs/loader:1126:14)
    at Module._extensions..js (internal/modules/cjs/loader:1180:10)
    at Module.load (internal/modules/cjs/loader:1004:32)
    at Module._load (internal/modules/cjs/loader:839:12)
    at executeUserEntryPoint (internal/modules/run_main:81:12)
    at <anonymous> (internal/main/run_main_module:17:47)

下面是我的代码:

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/mongotest')

下面是我的数据库连接:

这是我第一次尝试使用MongoDB,我对node.js和整个编程都很陌生,所以解决方案可能非常明显。

j0pj023g

j0pj023g1#

您的代码试图连接到运行在localhost(您的本地机器)上的MongoDB服务器,但是屏幕截图显示的是一个完全不同的主机名。
因此,请确保您实际使用的是正确的主机名:

mongoose.connect('mongodb://mydb.kngo05j.mongodb.net/mongotest')

您可能还需要传递登录凭据。如何操作请参见in the Mongoose documentation

92vpleto

92vpleto2#

在MAC上对我有用:

brew services restart mongodb/brew/mongodb-community@"yourmongoversion"

相关问题