首页 > 解决方案 > deno 到 mongodb 的连接失败

问题描述

我正在尝试将我的 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

标签: mongodbdeno

解决方案


我看到的2个问题:

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

要使其与 Mongo Atlas 一起使用,您需要调用具有不同参数的连接方法并找到正确的(静态)主机而不是(动态)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 或更高版本
  • 在这里,您将看到主机关注@字符的列表

推荐阅读