【问题标题】:unable to connect mongodb atlas with nodejs in a MERN project无法在 MERN 项目中将 mongodb atlas 与 nodejs 连接
【发布时间】:2021-08-05 17:48:53
【问题描述】:

显示错误

(node:7084) UnhandledPromiseRejectionWarning: Error: querySrv ETIMEOUT _mongodb._tcp.cluster0.ki2oq.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19)
(node:7084) 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:7084) [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.

使用的代码

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

require('dotenv').config();

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

app.use(cors());
app.use(express.json());

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})


app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});

谢谢

【问题讨论】:

    标签: javascript node.js mongodb mongoose mern


    【解决方案1】:

    您看到的错误是因为您没有在 mongoose.connect 上使用 try ... catch ...

    真正的问题是无法连接到远程 atlas 集群,这一定与您的 uri 有关。您是否在地图集设置中将您的 IP 地址或域列入白名单?如果您做了所有这些,请使用 atlas 配置管理员给出的确切 uri,并且不要使用现在在您的连接 uri 中使用的 useNewUrlParser 等属性。

    完整的答案可以在here 找到,包括正确使用try catch 和promise 拒绝处理。

    【讨论】:

      猜你喜欢
      • 2021-06-25
      • 2020-09-13
      • 1970-01-01
      • 2021-09-20
      • 2019-10-01
      • 2019-06-08
      • 2020-06-16
      • 1970-01-01
      • 2019-03-14
      相关资源
      最近更新 更多