Connection Guide连接指南

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

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, for the protocol, we use mongodb+srv which specifies the DNS Seedlist Connection Format. 在本例中,对于协议,我们使用mongodb+srv,它指定DNS种子列表连接格式This indicates that the hostname following it corresponds to the DNS SRV record of your MongoDB instance or deployment. 这表示它后面的主机名对应于MongoDB实例或部署的DNS SRV记录。If your instance or deployment does not have a DNS SRV record, use mongodb to specify the Standard Connection Format.如果您的实例或部署没有DNS SRV记录,请使用mongodb指定标准连接格式

Note

If your deployment is on MongoDB Atlas, follow the Atlas driver connection guide to retrieve your connection string.如果部署在MongoDB Atlas上,请按照Atlas驱动程序连接指南检索连接字符串。

The next part of the connection string contains your username and password if you are using password-based authentication. 如果使用基于密码的身份验证,则连接字符串的下一部分包含用户名和密码。Replace the value of user with your username and pass with your password. user的值替换为用户名,并使用密码传递。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 and port of your MongoDB instance. 连接字符串的下一部分指定MongoDB实例的主机名或IP地址和端口。In the example above, we use sample-hostname as the hostname and 27017 as the port. 在上面的示例中,我们使用sample-hostname作为主机名,使用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.有关连接选项的详细信息,请跳到“连接选项”部分。

The code below shows how you can use the sample connection URI in a client to connect to MongoDB.下面的代码显示了如何在客户端中使用示例连接URI连接到MongoDB。

const { MongoClient } = require("mongodb");
// Connection URI连接URI const uri = "mongodb+srv://sample-hostname:27017/?maxPoolSize=20&w=majority";
// Create a new MongoClient创建新的MongoClient const client = new MongoClient(uri);
async function run(){ try { // Connect the client to the server将客户端连接到服务器 await client.connect();
// Establish and verify connection建立并验证连接 await client.db("admin").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error确保完成/出错时客户端将关闭 await client.close(); } } run().catch(console.dir);

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服务器实例或副本集,请参阅以下部分了解如何连接。

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服务器的社区版企业版
  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 connection string "mongodb://localhost:<port>" where <port> is the port number you configured your server to listen for incoming connections.如果您的MongoDB服务器在本地运行,则可以使用连接字符串"mongodb://localhost:<port>"其中<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 Atlas code example and run it.要测试是否可以连接到服务器,请替换connect To MongoDB Atlas代码示例中的连接字符串并运行它。

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

You only need to specify one host to connect to a replica set. 只需指定一台主机即可连接到副本集。However, to ensure connectivity if the specified host is unavailable, provide the full list of hosts.但是,如果指定的主机不可用,为确保连接,请提供完整的主机列表。

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 it is not the primary member. 指定directConnection并连接到副本集的辅助成员时,写入操作将失败,因为它不是主成员。To perform read operations, you must enable secondary reads. 要执行读取操作,必须启用辅助读取。See the read preference options for more information.有关详细信息,请参阅“读取首选项”。

This section explains several common MongoDB connection and authentication options. 本节介绍几种常见的MongoDB连接和身份验证选项。You can pass the connection options as parameters of the connection URI to specify the behavior of the client.您可以将连接选项作为连接URI的参数传递,以指定客户端的行为。

Option Name选项名
Type类型
Default Value默认值
Description描述
connectTimeoutMS
integer
10000
Specifies the number of milliseconds to wait before timeout on a TCP connection.指定TCP连接超时前等待的毫秒数。
family
number
null
Specifies the version of the Internet Protocol (IP). 指定Internet协议(IP)的版本。The valid values are: 4, 6, 0, or null. The 0 and null settings attempt to connect with IPv6 and fall back to IPv4 upon failure.有效值为:460null0null设置尝试连接IPv6,并在失败时返回IPv4。
forceServerObjectId
boolean
false
Specifies whether to force the server to assign _id values to documents instead of the driver.指定是否强一致性务器将_id值分配给文档而不是驱动程序。
ignoreUndefined
boolean
false
Specifies whether the BSON serializer should ignore undefined fields.指定BSON序列化程序是否应忽略未定义的字段。
keepAlive
boolean
true
Specifies whether to enable keepAlive on the TCP socket. 指定是否在TCP套接字上启用keepAliveFor more information, see the documentation for Node.js socket.setKeepAlive.有关更多信息,请参阅Node.js socket.setKeepAlive的文档。
keepAliveInitialDelay
integer
120000
Specifies the number of milliseconds to wait before initiating keepAlive on the TCP socket. 指定在TCP套接字上启动keepAlive之前等待的毫秒数。For more information, see the documentation for Node.js socket.setKeepAlive.有关更多信息,请参阅Node.js socket.setKeepAlive的文档。
logger
object
null
Specifies a custom logger for the client to use.指定客户端要使用的自定义记录器。
loggerLevel
string
null
Specifies the logger level used by the driver. Valid choices are: error, warn, info, and debug.指定驱动程序使用的记录器级别。有效选项包括:errorwarninginfodebug
maxPoolSize
integer
100
Specifies the maximum number of connections that a connection pool may have at a given time.指定连接池在给定时间可能具有的最大连接数。
maxIdleTimeMS
integer
Specifies the maximum amount of time a connection can remain idle in the connection pool before being removed and closed.指定删除和关闭连接之前连接在连接池中保持空闲的最长时间。
minPoolSize
integer
0
Specifies the minimum number of connections that must exist at any moment in a single connection pool.指定单个连接池中任何时刻必须存在的最小连接数。
noDelay
boolean
true
Specifies whether to use the TCP socket no-delay option. 指定是否使用TCP套接字无延迟选项。For more information, see the documentation for Node.js socket.setNoDelay.有关更多信息,请参阅Node.js socket.setNoDelay的文档。
pkFactory
object
null
Specifies a primary key factory object that generates custom _id keys.指定生成自定义_id键的主键工厂对象。
promiseLibrary
object
null
Specifies the Promise library class the application uses (e.g. Bluebird). 指定应用程序使用的Promise库类(例如Bluebird)。This library must be compatible with ES6.此库必须与ES6兼容。
promoteBuffers
boolean
false
Specifies whether to promote Binary BSON values to native Node.js Buffer type data.指定是否将二进制BSON值升级为本机Node.jsBuffer类型数据。
promoteLongs
boolean
true
Specifies whether to convert Long values to a number if they fit inside 53 bits of resolution.指定如果Long值在53位分辨率内,是否将其转换为数字。
promoteValues
boolean
true
Specifies whether to promote BSON values to Node.js native types when possible. 指定是否尽可能将BSON值升级为Node.js本机类型。When set to false, it uses wrapper types to present BSON values.当设置为false时,它使用包装器类型来表示BSON值。
raw
boolean
false
Specifies whether to return document results as raw BSON buffers.指定是否将文档结果作为原始BSON缓冲区返回。
serializeFunctions
boolean
false
Specifies whether to serialize functions on any object passed to the server.指定是否序列化传递给服务器的任何对象上的函数。
serverApi
string or enum
null
Specifies the API version that operations must conform to. 指定操作必须符合的API版本。See the MongoDB manual entry on Versioned API for more information.有关更多信息,请参阅版本化API上的MongoDB手册条目。
socketTimeoutMS
integer
360000
Specifies the number of milliseconds to wait before timeout on a TCP socket.指定TCP套接字超时前等待的毫秒数。
tls
boolean
false
Specifies whether to establish a Transport Layer Security (TLS) connection with the instance. 指定是否与实例建立传输层安全性(TLS)连接。This is automatically set to true when using a DNS seedlist (SRV) in the connection string. 当在连接字符串中使用DNS种子列表(SRV)时,这会自动设置为trueYou can override this behavior by setting the value to false.可以通过将值设置为false来覆盖此行为。
validateOptions
boolean
false
Specifies whether to error when the method parameters contain an unknown or incorrect option. If false, the driver produces warnings only.指定当方法参数包含未知或不正确的选项时是否出错。如果为false,则驱动程序仅生成警告。
waitQueueTimeoutMS
integer
0
Specifies the maximum amount of time in milliseconds that operation execution can wait for a connection to become available.指定操作执行可以等待连接可用的最长时间(毫秒)。
writeConcern
string or integer
null
Specifies the write concern. 指定写入关注点。For more information on values, see the server documentation on the w Option.有关值的更多信息,请参阅关于w选项的服务器文档。
directConnection
boolean
false
Specifies whether to force dispatch all operations to the host specified in the connection URI.指定是否强制将所有操作分派到连接URI中指定的主机。

For a complete list of options, see the MongoClient API reference page.有关选项的完整列表,请参阅MongoClient API参考页面。