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

问题描述

我尝试按照本教程https://www.youtube.com/watch?v=VF38U2qd27Q进行操作,但无济于事。我意识到视频中的语法已经过时,例如 connectWithUri 变成了连接。

但是当我尝试使用deno_mongo和最新的文档连接到 mongo 时,它仍然无法正常工作。

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

const dbString = `mongodb://${mongoUser}:${mongoPass}@${mongoHost}:${mongoPort}`;
const client = new MongoClient();
client.connect(dbString);
const db = client.database(mongoDB)
this.users = db.collection<UserSchema>("users");

然后我找到了另一个库denodb但再次无法连接到 mongodb:

import { Database } from 'https://deno.land/x/denodb/mod.ts';

const dbString = `mongodb://${mongoUser}:${mongoPass}@${mongoHost}:${mongoPort}`;
this.db = new Database('mongo', {
  uri: dbString,
  database: mongoDB
});

错误信息:

error: Uncaught AssertionError
deno        |     throw new AssertionError(msg);
deno        |           ^
deno        |     at assert (asserts.ts:152:11)
deno        |     at MongoClient.database (client.ts:48:5)
deno        |     at new connectDB (connectDB.ts:35:23)

哪一部分是错的?

标签: mongodbdeno

解决方案


查看GitHub 上的 deno_mongo 自述文件。

对于本地数据库,您应该使用

//Connecting to a Local Database
await client.connect("mongodb://localhost:27017");

如果您要连接到 Mongo Atlas 数据库(可能还有任何其他远程数据库),您应该使用:

//Connecting to a Mongo Atlas Database
await client.connect({
  db: "<db_name>",
  tls: true,
  servers: [
    {
      host: "<db_cluster_url>",
      port: 27017,
    },
  ],
  credential: {
    username: "<username>",
    password: "<password>",
    db: "<db_name>",
    mechanism: "SCRAM-SHA-1",
  },
});

供参考

如果您使用的是 Mongo Atlas,请确保将您从 Mongo Atlas 仪表板中的“连接向导”获得的连接字符串拆分为服务器阵列中的 3 个(或您拥有多少个副本)条目。像这样:

servers: [
  {
    host: this.dbUrl1, // e.g. <name-of-cluster>-00-00.fbnrc.mongodb.net
    port: 27017,
  },
  {
    host: this.dbUrl2, // e.g. <name-of-cluster>-00-01.fbnrc.mongodb.net
    port: 27017,
  },
  {
    host: this.dbUrl3, // e.g. <name-of-cluster>-00-02.fbnrc.mongodb.net
    port: 27017,
  }
]

您通过以下方式获取连接字符串:

  • 单击数据存储下的“集群”(屏幕左侧)
  • 点击“连接”按钮
  • 单击“连接到应用程序”
  • 选择驱动程序:“Node.js”和版本:“2.2.12 或更高版本”

连接字符串如下所示。服务器以逗号分隔的方式列出,如下所示:

...<name-of-cluster>-00-00.fbnrc.mongodb.net:27017,<name-of-cluster>-00-01.fbnrc.mongodb.net:27017,<name-of-cluster>-00-02.fbnrc.mongodb.net:27017...

仅供参考-2

确保主副本列在服务器阵列的首位。因为如果您想插入数据库,则应该以主副本为目标。对我来说,这是第二个 mongo url,因此以下服务器数组对我有用:

servers: [
  {
    host: this.dbUrl2,
    port: 27017,
  },
  {
    host: this.dbUrl1,
    port: 27017,
  },
  {
    host: this.dbUrl3,
    port: 27017,
  }
]

推荐阅读