提问者:小点点

MongoDB Atlas与Mongoose连接时出现超时错误


我正在尝试使用Mongoose连接到MongoDB Atlas上的数据库。 但每次它都会给我以下错误:

(node:2327) UnhandledPromiseRejectionWarning: Error: queryTxt ETIMEOUT cluster0-abjwg.gcp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:206:19)
(node:2327) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2327) [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.

我试过将IP列入白名单。 同样,同样的代码在另一台机器上运行良好,但在我的机器上却不行。

代码是:

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

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

// Connecting to MongoDB
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true});
const connection = mongoose.connection;
connection.once('open', () => {
    console.log('Connection established');
})

app.use(express.json());

app.listen(port, () => {
    console.log(`Here we go on port: ${port}`);
});

它应该给出输出:

Here we go on port: 5000
Connection established

但我得到的是唯一的第一个输出和错误。


共1个答案

匿名用户

它与其说是一个错误,不如说是一个警告,在第二行中描述了正在发生的情况:这个错误是由不带catch块的异步函数内部引发的,或者是由拒绝一个没有用。catch()处理的承诺引起的。
您必须始终处理连接失败时发生的错误。 在您的示例中,您必须添加connection.on('error',console.error.bind(console,'connection error:'));以在连接不成功时处理错误。

在使用承诺的情况下:

mongoose.connect(uri,{useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true})
.then(() => console.log("Connection Established")
.catch((err) => //handle error)

如果使用Async/Await:

try {
await mongoose.connect(uri,{useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true})
console.log("Connection Established")
} catch(e) {
//handle error
}