繁体   English   中英

Node.Js 和 MongoDB Compass 连接错误

[英]Node.Js and MongoDB Compass connection error

我正在尝试连接到 MongoDB Compass。 我正在使用 Typescript、Node.Js 和 Mongoose 进行连接,但是在尝试连接时出现错误。

这是我的 mongo 连接代码

const url ='mongodb://localhost:27017/BlogApp';

mongoose.connect(url)
.then(() => {console.log("Connected to MongoDB")})
.catch((err) => console.log(err));

 //*** BEEP BOOP ***//
 app.listen(PORT, () => {
    console.log(`Your server available at http://localhost:${PORT}`);
})

我的服务器正常启动并正常运行,但是与 MongoDB 的连接给了我这个巨大的错误,我不知道它有什么问题。

    MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at NativeConnection.Connection.openUri (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\connection.js:819:32)
    at C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\index.js:377:10
    at C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\index.js:1220:10)
    at Mongoose.connect (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\index.js:376:20)
    at Object.<anonymous> (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\index.ts:31:10)
    at Module._compile (node:internal/modules/cjs/loader:1112:14)
    at Module.m._compile (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\ts-node\src\index.ts:1597:23) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  },
  code

我使用与其他项目相同的设置(我只是复制了代码),但这次它没有连接。 我的旧项目使用相同的后端设置,这次我只为打字稿重写了它。

我不知道您使用的是哪个版本的 mongoose 或 mongoDB,但您需要告诉 mongoose 如何“查找”连接,以便您的代码看起来像这样。 我不确定它到底是如何工作的,但你需要告诉猫鼬用 IPv4 而不是 IPv6 来查看(不知道为什么)

const url = 'mongodb://localhost:27017/BlogApp';
const options = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    family: 4 // Use IPv4, skip trying IPv6
}
mongoose.Promise = global.Promise;
mongoose.connect(url!, options)
.then(() => {console.log("Connected to MongoDB")})
.catch((err) => console.log(err));


 //*** BEEP BOOP ***//
 app.listen(PORT, () => {
    console.log(`Your server available at http://localhost:${PORT}`);
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM