【问题标题】:connection of deno to mongodb failsdeno 到 mongodb 的连接失败
【发布时间】:2021-05-09 22:56:38
【问题描述】:

我正在尝试将我的 deno 应用程序连接到 mongodb,但出现错误。

import {MongoClient} from "https://deno.land/x/mongo@v0.21.2/mod.ts";

const client = await new MongoClient();
await client.connect("mongodb+srv://deno:i4vY8AtCEhr6ReqB@sample.7jp1l.mongodb.net/deno?retryWrites=true&w=majority");

const db = client.database("notes");

export default db;

一切似乎都很好,但是当我运行应用程序时,我收到了这个错误。

error: Uncaught (in promise) Error: MongoError: "Connection failed: failed to lookup address information: nodename nor servname provided, or not known"
                throw new MongoError(`Connection failed: ${e.message || e}`);
              ^
    at MongoClient.connect (client.ts:93:15)
    at async mongodb.ts:4:1

【问题讨论】:

  • 仔细检查
  • 查找地址信息失败: - 我不认为这是您的代码或 Deno 的问题,而只是一个无法访问的地址。尝试使用本地数据库。
  • 有同样的问题
  • 我也有同样的问题
  • URL 似乎有问题。

标签: mongodb deno


【解决方案1】:

我看到的2个问题:

  • 上面的代码 sn-p 只适用于本地机器上安装的 Mongo。
  • 连接字符串使用 DNS 种子列表,但当前库无法解析为主机列表

要使其与 Mongo Atlas 一起使用,您需要调用具有不同参数的 connect 方法并找到正确的(静态)主机而不是(动态)DNS 种子列表:

const client = new MongoClient();

const db = await client.connect({
  db: '<your db or collection with work with>',
  tls: true,
  servers: [
    {
      host: '<correct host - the way to get the host - see bellow>',
      port: 27017,
    },
  ],
  credential: {
    username: '<your username>',
    password: '<your password>',
    mechanism: 'SCRAM-SHA-1',
  },
});

如何获取正确的主机:

  • 在 Mongo Atlas 中打开您的集群
  • 选择连接按钮
  • 选择连接到应用程序选项
  • 选择驱动程序:Node.js 和版本:2.2.12 或更高版本
  • 在这里你会看到一个主机跟随@字符的列表

【讨论】:

    【解决方案2】:

    感谢@nthung.vlvn 提供线索。实际上,主机需要是主分片。它修复了lookup address information,但我遇到了另一个错误,即我的凭据不正确。我必须将 db "admin" 添加到凭据中:

    credential: {
        username: '<your username>',
        password: '<your password>',
        db: "admin",
        mechanism: 'SCRAM-SHA-1',
    }
    

    这很奇怪,因为我的 Atlas 中没有 admin db。不管怎样,它开始起作用了。

    【讨论】:

      猜你喜欢
      • 2021-04-05
      • 1970-01-01
      • 2017-02-11
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 2017-10-05
      相关资源
      最近更新 更多