选择连接目标
Overview
在本指南中,您可以学习;了解如何使用连接string和 MongoClient
对象连接到不同类型的MongoDB部署。
提示
要详细学习;了解如何检索连接字符串,请参阅Atlas文档中的 Connect via Drivers(通过驱动程序连接)指南。
Atlas
要连接到MongoDB 上的Atlas 部署,请在连接string 中包含以下元素:
Atlas 集群的 URL
MongoDB 用户名
MongoDB 密码
然后,将连接string传递给 MongoClient
构造函数。
当您连接到Atlas时,我们建议使用 Stable API客户端选项,以避免Atlas升级到新版本的MongoDB Server时发生重大更改。 要学习;了解有关 Stable API功能的更多信息,请参阅 Stable API指南。
以下代码演示了如何使用 Node.js驾驶员连接到Atlas 集群。该代码还使用 server_api
字段来指定 Stable API版本。
const { MongoClient, ServerApiVersion } = require("mongodb"); // Replace the placeholder with your Atlas connection string const uri = "<connection string>"; // Creates a MongoClient with a MongoClientOptions object to set the Stable API version const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } } ); async function run() { try { // Connects the client to the server (optional starting in v4.7) await client.connect(); // Sends a ping to confirm a successful connection await client.db("admin").command({ ping: 1 }); console.log("Pinged your deployment. You successfully connected to MongoDB!"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
本地部署
要连接到本地独立运行的MongoDB 部署,请指定服务器的托管。(可选)指定服务器的端口。如果未指定端口,默认端口为 27017
。
您可以使用连接字符串指定要连接的托管和端口,如以下代码所示:
const client = new MongoClient("mongodb://host1:27017");
您也可以将托管指定为 localhost
。以下代码示例连接到指定端口上的 localhost
:
const client = new MongoClient("mongodb://localhost:27017");
副本集
要连接到副本集,我们建议您指定属于副本集的所有节点。如果一个或多个节点不可用,通过指定所有节点,驾驶员仍可在一个节点可用的情况下连接到副本集。
但是,副本集集中任一节点的解决传递给驾驶员就足够了。该节点不一定是主节点 (primary node in the replica set),也可以是隐藏节点。然后,驾驶员将自动发现剩余节点。
以下示例展示了如何使用连接字符串连接到副本集,以及如何使用 replicaSet
连接字符串选项在连接时验证副本集名称:
const client = new MongoClient("mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRs");
注意
Docker 中的副本集
当副本集在Docker中运行时,它可能只公开一个MongoDB端点。在这种情况下,无法发现副本集。在连接 URI 中指定 directConnection=false
或未设置此选项,可能会阻止应用程序与之连接。
在测试或开发环境中,您可以通过指定 directConnection=true
来连接到副本集。在生产环境中,我们建议配置集群,以便每个 MongoDB 实例都可以在 Docker 虚拟网络之外访问。
API 文档
要学习;了解有关使用 Node.js驾驶员创建 MongoClient
对象的更多信息,请参阅 MongoClient 的API文档。