【问题标题】:MongoDB Mongoose error when connecting to the databaseMongoDB Mongoose 连接数据库时出错
【发布时间】:2020-09-08 12:47:00
【问题描述】:

我在使用 Mongoose 连接到 MongoDB 数据库时遇到了问题。我正在使用 node js 和 express。

这是错误:

Error: queryTxt ESERVFAIL businessregistration-npeym.mongodb.net


(node:66755) UnhandledPromiseRejectionWarning: Error: queryTxt ESERVFAIL businessregistration-npeym.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:206:19)
(node:66755) 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)

我认为主要的错误是: Error: queryTxt ESERVFAIL businessregistration-npeym.mongodb.net

我的代码:

const express = require("express");
const app = express();

const Schema = require("./Schema");
const mongoose = require("mongoose");
const port = process.env.PORT || 4000;

mongoose.connect(
  "mongodb+srv://<username>:<password>@businessregistration-npeym.mongodb.net/test?retryWrites=true&w=majority",
  { useNewUrlParser: true, useUnifiedTopology: true }
);

mongoose.connection.on("connected", function () {
  console.info("Connected!\n\n");
});
mongoose.connection.on("error", function (err) {
  console.error(`ERROR!!! The error is: ${err}\n\n`); // error is consoled here
});
mongoose.connection.on("disconnected", function () {
  console.warn(
    "The connection has been lost. This is because it got disconnected.\n\n"
  );
});

app.listen(port, () => {
  console.log(`Listening on port ${port}!`);
});

我不知道为什么会突然发生这种情况。如果你能帮忙,谢谢!

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    经过一番研究,滚动浏览堆栈溢出,我终于找到了解决方案。

    来自堆栈溢出的 JOSEPH KASULE 的功劳:Thanks!

    回答链接:How to fix 'Error: querySrv EREFUSED' when connecting to MongoDB Atlas?

    向下滚动到正确答案以找到它。

    事实证明,我必须使用较旧的连接方法进行连接。我必须选择 2.2.12 或更高版本的节点版本:

    我必须使用旧版本的连接:

    而不是这个:

    mongodb+srv://<username>:<password>@businessregistration-npeym.mongodb.net/test?retryWrites=true&w=majority
    

    我不得不使用这个:

    mongodb://<username>:<password>@businessregistration-shard-00-00-npeym.mongodb.net:27017,businessregistration-shard-00-01-npeym.mongodb.net:27017,businessregistration-shard-00-02-npeym.mongodb.net:27017/test?ssl=true&replicaSet=BusinessRegistration-shard-0&authSource=admin&retryWrites=true&w=majority
    

    当使用 mongoose 连接到 Mongo DB 时。

    原因是根据 Mongo DB 的说法,由于 Mongoose,SRV 无法正常工作。

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 2020-12-28
      • 2014-07-18
      • 2017-06-29
      • 2020-10-26
      相关资源
      最近更新 更多