mongodb - 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
解决方案
我看到的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 或更高版本
- 在这里,您将看到主机关注@字符的列表
推荐阅读
- airflow - 气流任务失败/重试工作流程
- javascript - Chart.js:如何在鼠标悬停时改变线条系列(在众多线条中)的颜色和粗细?
- postgresql - Postgres:SELECT FOR UPDATE 在锁定释放后看不到新行
- kotlin - 未调用 ktor 中的应用程序级事件
- java - 无法将扫描仪转换为文件,扫描仪位于文件末尾,fileNotFoundException
- java - 在 IDEA 中,如何自动删除 .attach_pidxxx 文件
- swift4 - 如何处理标准和自定义 Swift 4 Decodable 属性的混合?
- r - 平均(或任何其他统计)计算省略零
- javascript - 从 href="path/of/file..WAV" 在 VLC 中打开文件
- reactjs - 如何从另一个用于 SSO 的 UI 应用程序获取 React 应用程序中的密钥(访问令牌)