Docs HomeNode.js

Connection Guide连接指南

This guide shows you how to connect to a MongoDB instance or replica set using the Node.js driver.本指南向您展示如何使用Node.js驱动程序连接到MongoDB实例或副本集。

Connection URI连接URI

The connection URI is the set of instructions that the driver uses to connect to a MongoDB deployment. 连接URI是驱动程序用来连接到MongoDB部署的一组指令。It instructs the driver on how it should connect to MongoDB and how it should behave while connected. 它指导驱动程序如何连接到MongoDB,以及连接时的行为。The following example shows each part of the connection URI:以下示例显示了连接URI的每个部分:

Each part of the connection string

In this example, we use mongodb for the protocol, which specifies the Standard Connection String Format.在本例中,我们使用mongodb作为协议,它指定了标准连接字符串格式

If your instance or deployment has a DNS SRV record, you can use the DNS Seed List Connection Format for your connection string. 如果您的实例或部署具有DNS SRV记录,则可以对连接字符串使用DNS种子列表连接格式This format offers more flexibility of deployment and the ability to change the servers in rotation without reconfiguring clients.这种格式提供了更大的部署灵活性,并且能够在不重新配置客户端的情况下轮流更改服务器。

Note

To learn how to retrieve your connection string in Atlas, see the Atlas driver connection guide.要了解如何在Atlas中检索连接字符串,请参阅Atlas驱动程序连接指南

The next part of the connection string contains your credentials if you are using password-based authentication. 如果您使用基于密码的身份验证,则连接字符串的下一部分包含您的凭据。Replace the value of user with your username and pass with your password. user的值替换为您的用户名,并使用您的pass进行传递。If you are using an authentication mechanism that does not require a username and password, omit this part of the connection URI.如果您使用的身份验证机制不需要用户名和密码,请省略连接URI的这一部分。

The next part of the connection string specifies the hostname or IP address of your MongoDB instance, followed by the port number. 连接字符串的下一部分指定MongoDB实例的主机名或IP地址,后跟端口号。In the example above, we use sample.host as the hostname and 27017 as the port. 在上面的示例中,我们使用sample.host作为主机名,27017作为端口。Replace these values to point to your MongoDB instance.将这些值替换为指向您的MongoDB实例。

The last part of the connection string contains connection and authentication options as parameters. 连接字符串的最后一部分包含作为参数的连接和身份验证选项。In the example above, we set two connection options: maxPoolSize=20 and w=majority. 在上面的例子中,我们设置了两个连接选项:maxPoolSize=20w=majorityFor more information on connection options, skip to the Connection Options section.有关连接选项的详细信息,请跳到连接选项部分。

Atlas Connection ExampleAtlas连接示例

You must create a client to connect to a MongoDB deployment on Atlas. 您必须创建一个客户端才能连接到Atlas上的MongoDB部署。To create a client, construct an instance of MongoClient, passing in your URI and a MongoClientOptions object.要创建客户端,请构造MongoClient的实例,传入URI和MongoClientOptions对象。

Tip

Reuse Your Client重用您的客户端

As each MongoClient represents a pool of connections to the database, most applications only require a single instance of a MongoClient, even across multiple requests. 由于每个MongoClient代表一个到数据库的连接池,因此大多数应用程序只需要MongoClient的一个实例,甚至跨多个请求。To learn more about how connection pools work in the driver, see the FAQ page.要了解有关连接池如何在驱动程序中工作的更多信息,请参阅常见问题页面

Use the serverApi option in your MongoClientOptions object to enable the Stable API feature, which forces the server to run operations with behavior compatible with the specified API version.使用MongoClientOptions对象中的serverApi选项启用Stable API功能,该功能强一致性务器运行行为与指定API版本兼容的操作。

The following code shows how you can specify the connection string and the Stable API client option when connecting to a MongoDB deployment on Atlas and verify that the connection is successful:以下代码显示了如何在连接到Atlas上的MongoDB部署时指定连接字符串和Stable API客户端选项,并验证连接是否成功:

const { MongoClient, ServerApiVersion } = require("mongodb");

// Replace the placeholder with your Atlas connection string将占位符替换为Atlas连接字符串
const uri = "<connection string>";

// Create a MongoClient with a MongoClientOptions object to set the Stable API version创建一个带有MongoClientOptions对象的MongoClient来设置Stable API版本
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
}
);

async function run() {
try {
// Connect the client to the server (optional starting in v4.7)将客户端连接到服务器(可选,从v4.7开始)
await client.connect();

// Send a ping to confirm a successful connection发送ping以确认连接成功
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);

To learn more about the Stable API feature, see the Stable API page.要了解有关Stable API功能的更多信息,请参阅Stable API页面

Other Ways to Connect to MongoDB连接MongoDB的其他方法

If you are connecting to a single MongoDB server instance or replica set that is not hosted on Atlas, see the following sections to find out how to connect.如果您要连接到一个未托管在Atlas上的MongoDB服务器实例或副本集,请参阅以下部分了解如何连接。

Connect to a MongoDB Server on Your Local Machine连接到本地计算机上的MongoDB服务器

If you need to run a MongoDB server on your local machine for development purposes instead of using an Atlas cluster, you need to complete the following:如果您需要在本地机器上运行MongoDB服务器进行开发,而不是使用Atlas集群,则需要完成以下操作:

  1. Download the Community or Enterprise version of MongoDB Server.下载MongoDB Server的社区版企业版
  2. Install and configure MongoDB Server.安装和配置MongoDB服务器。
  3. Start the server.启动服务器。
Important

Always secure your MongoDB server from malicious attacks. 始终保护您的MongoDB服务器免受恶意攻击。See our Security Checklist for a list of security recommendations.有关安全建议的列表,请参阅安全检查表

After you successfully start your MongoDB server, specify your connection string in your driver connection code.成功启动MongoDB服务器后,在驱动程序连接代码中指定连接字符串。

If your MongoDB Server is running locally, you can use the following connection string:如果您的MongoDB服务器在本地运行,您可以使用以下连接字符串:

mongodb://localhost:<port>

In this connection string, <port> is the port number on which you configured your server to listen for incoming connections.在此连接字符串中,<port>是您将服务器配置为侦听传入连接的端口号。

If you need to specify a different hostname or IP address, see our Server Manual entry on Connection Strings.如果您需要指定不同的主机名或IP地址,请参阅连接字符串中的“服务器手册”条目。

To test whether you can connect to your server, replace the connection string in the Connect to MongoDB code example and run it.要测试是否可以连接到服务器,请替换连接到MongoDB代码示例中的连接字符串并运行它。

Connect to a Replica Set连接到副本集

A MongoDB replica set deployment is a group of connected instances that store the same set of data. MongoDB副本集部署是一组存储相同数据集的连接实例。This configuration of instances provides data redundancy and high data availability.实例的这种配置提供了数据冗余和高数据可用性。

To connect to a replica set deployment, specify the hostname and port numbers of each instance, separated by a comma, and the replica set name as the value of the replicaSet parameter in the connection string.要连接到副本集部署,请指定每个实例的主机名和端口号(用逗号分隔),并将副本集名称指定为连接字符串中replicaSet参数的值。

mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRs

When making a connection, the driver takes the following actions by default:在进行连接时,默认情况下,驱动程序会执行以下操作:

  • Discovers all replica set members when given the address of any one member.当给定任何一个成员的地址时,查找所有复制副本集成员。
  • Dispatches operations to the appropriate member, such as write against the primary.将操作分派给适当的成员,例如针对成员进行写操作。
Tip

Specify all hosts指定所有主机

To ensure connectivity if one host is unavailable, provide the full list of hosts when connecting to a replica set.要确保在一个主机不可用时的连接,请在连接到复制副本集时提供主机的完整列表。

Direct Connection直接连接

To force your operations to run on the host specified in your connection URI, you can specify the directConnection connection option. 若要强制操作在连接URI中指定的主机上运行,可以指定directConnection连接选项。If you specify this option, you must use the standard connection URI format. 如果指定此选项,则必须使用标准连接URI格式。The driver does not accept the DNS seedlist connection format (SRV) when you specify this option.指定此选项时,驱动程序不接受DNS种子列表连接格式(SRV)。

When you specify directConnection and connect to a secondary member of the replica set, your write operations fail because the client isn't connected to the primary member. 指定directConnection并连接到副本集的辅助成员时,由于客户端未连接到主成员,写入操作将失败。To perform read operations, you must enable secondary reads. 要执行读取操作,必须启用辅助读取。See the read preference options for more information.有关详细信息,请参阅读取首选项