Docs Home / Node.js / Connect / Connection Options

Limit Server Execution Time限一致性务器执行时间

Overview概述

When you use the Node.js driver to perform a server operation, you can also limit the duration allowed for the server to finish the operation. To do so, specify a client-side operation timeout (CSOT). The timeout applies to all steps needed to complete the operation, including server selection, connection checkout, and server-side execution. When the timeout expires, the Node.js driver raises a timeout exception.当您使用Node.js驱动程序执行服务器操作时,您还可以限一致性务器完成操作所允许的持续时间。为此,请指定客户端操作超时(CSOT)。超时适用于完成操作所需的所有步骤,包括服务器选择、连接签出和服务器端执行。当超时到期时,Node.js驱动程序会引发超时异常。

Note

Experimental Feature实验特性

The CSOT feature is experimental and might change in future driver releases.CSOT功能是实验性的,可能会在未来的驱动程序版本中发生变化。

timeoutMS Option选项

To specify a timeout when connecting to a MongoDB deployment, set the timeoutMS connection option to the timeout length in milliseconds. You can do this in two ways: by passing an argument to the MongoClient constructor or through a parameter in your connection string.要指定连接到MongoDB部署时的超时,请将timeoutMS连接选项设置为超时长度(毫秒)。您可以通过两种方式做到这一点:将参数传递给MongoClient构造函数,或通过连接字符串中的参数。

The following code examples use the timeoutMS option to specify a timeout of 30 seconds:以下代码示例使用timeoutMS选项指定超时30秒:

MongoClient
const uri = "mongodb://<hostname>:<port>";
const client = new MongoClient(uri, { timeoutMS: 30000 });
Connection String
const uri = "mongodb://<hostname>:<port>?timeoutMS=30000";
const client = new MongoClient(uri);

Note

The timeoutMS connection option takes precedence over the following options:timeoutMS连接选项优先于以下选项:

  • socketTimeoutMS
  • waitQueueTimeoutMS
  • wTimeoutMS
  • maxTimeMS
  • maxCommitTimeMS

When the CSOT feature is no longer experimental, the preceding options will be deprecated.当CSOT功能不再处于试验阶段时,上述选项将被弃用。

If you specify the timeoutMS option, the driver automatically applies the specified timeout per each server operation. The following code example specifies a timeout of 10 seconds at the client level, and then calls the insertOne() method:如果指定timeoutMS选项,驱动程序将自动为每次服务器操作应用指定的超时。以下代码示例在客户端级别指定了10秒的超时,然后调用insertOne()方法:

const uri = "<connection string uri>";
const client = new MongoClient(uri, {
timeoutMS: 10000
});

async function run() {
try {
const db = client.db("test-db");
const coll = db.collection("test-collection");

const result = await coll.insertOne({ name: "Yngwie" });
console.log("Insert result:", result);
} finally {
await client.close();
}
}

run().catch(console.dir);

Timeout Inheritance超时继承

When you specify a timeoutMS option, the driver applies the timeout according to the same inheritance behaviors as the other Node.js driver options. The following table describes how the timeout value is inherited at each level:当您指定timeoutMS选项时,驱动程序将根据与其他Node.js驱动程序选项相同的继承行为应用超时。下表描述了如何在每个级别继承超时值:

Level级别Inheritance Description继承描述
Operation操作Takes the highest precedence and will override timeoutMS options set at any other level.具有最高优先级,并将覆盖在任何其他级别设置的timeoutMS选项。
TransactionTakes precedence over timeoutMS set at the session, collection, database, or client level.优先于在会话、集合、数据库或客户端级别设置的timeoutMS
SessionApplies to all transactions and operations within that session, unless the option is overridden by options set at those levels.适用于该会话中的所有事务和操作,除非该选项被设置在这些级别的选项覆盖。
DatabaseApplies to all sessions and operations within that database, unless the option is overridden by options set at those levels.适用于该数据库中的所有会话和操作,除非该选项被在这些级别设置的选项覆盖。
CollectionApplies to all sessions and operations on that collection, unless the option is overridden by options set at those levels.适用于该集合上的所有会话和操作,除非该选项被在这些级别设置的选项覆盖。
ClientApplies to all databases, collections, sessions, transactions, and operations within that client that do not otherwise specify timeoutMS.适用于该客户端中未指定timeoutMS的所有数据库、集合、会话、事务和操作。

For more information on overrides and specific options, see the Overrides section.有关替代和特定选项的更多信息,请参阅替代部分。

Overrides替代

The Node.js driver supports various levels of configuration to control the behavior and performance of database operations.Node.js驱动程序支持各种级别的配置,以控制数据库操作的行为和性能。

You can specify a timeoutMS option at the operation level to override the client-level configuration for a specific operation. This allows you to customize timeouts based on the needs of individual queries.您可以在操作级别指定timeoutMS选项,以覆盖特定操作的客户端级别配置。这允许您根据单个查询的需要自定义超时。

The following example demonstrates how an operation-level timeoutMS configuration can override a client-level timeoutMS configuration:以下示例演示了操作级timeoutMS配置如何覆盖客户端级timeoutMS配置:

// Creates a new MongoClient with a client-level timeoutMS configuration使用客户端级timeoutMS配置创建新的MongoClient
const uri = "<connection string uri>";
const client = new MongoClient(uri, {
// Client-level timeout: 15 seconds客户端级超时:15秒
timeoutMS: 15000
});

async function run() {
try {
const db = client.db("test-db");
const coll = db.collection("test-collection");

// Performs a query operation with an operation-level timeoutMS configuration使用操作级timeoutMS配置执行查询操作
const docs = await coll.find({},
// Operation-level timeout: 10 seconds操作级别超时:10秒
{ timeoutMS: 10000 })
.toArray();

console.log(docs);
} finally {
await client.close();
}
}

run().catch(console.dir);

Transactions事务

When you create a new ClientSession instance to implement a transaction, use the defaultTimeoutMS option. You can set defaultTimeoutMS to specify the timeoutMS values to use for:当您创建新的ClientSession实例来实现事务时,请使用defaultTimeoutMS选项。您可以设置defaultTimeoutMS来指定用于以下操作的timeoutMS值:

If you do not specify defaultTimeoutMS, the driver uses the timeoutMS value set on the parent MongoClient.如果不指定defaultTimeoutMS,驱动程序将使用在父MongoClient上设置的timeoutMS值。

You cannot override defaultTimeoutMS by setting the timeoutMS option on an operation in a transaction session provided by the withTransaction() callback. Doing so throws an error.您不能通过在withTransaction()回调提供的事务会话中的操作上设置timeoutMS选项来覆盖defaultTimeoutMS。这样做会引发错误。

Client Encryption客户端加密

When you use Client-Side Field Level Encryption (CSFLE), the driver uses the timeoutMS option to limit the time allowed for encryption and decryption operations.当您使用客户端字段级加密(CSFLE)时,驱动程序会使用timeoutMS选项来限制加密和解密操作所允许的时间。

If you specify the timeoutMS option when you construct a ClientEncryption instance, it controls the lifetime of all operations performed on that instance. 如果在构造ClientEncryption实例时指定timeoutMS选项,则它将控制在该实例上执行的所有操作的生存期。If you do not provide timeoutMS, the instance inherits the timeoutMS setting from the MongoClient used in the ClientEncryption constructor.如果不提供timeoutMS,则实例将继承ClientEncryption构造函数中使用的MongoClienttimeoutMS设置。

If you set timeoutMS on both the client and directly in ClientEncryption, the value provided to ClientEncryption takes precedence.如果在客户端和直接在ClientEncryption中设置timeoutMS,则提供给ClientEncryption的值优先。

Cursors游标

Cursors offer configurable timeout settings when using the CSOT feature. You can adjust cursor handling by configuring either the cursor lifetime or cursor iteration mode if needed. 使用CSOT功能时,游标提供可配置的超时设置。如果需要,您可以通过配置游标生存期或游标迭代模式来调整游标处理。To configure the mode, set the timeoutMode option to cursorLifetime, which is the default, or iteration.要配置模式,请将timeoutMode选项设置为cursorLifetime(默认值)或iteration

Cursor Lifetime Mode游标生存期模式

The cursor lifetime mode uses timeoutMS to limit the entire lifetime of a cursor. In this mode, the initialization of the cursor and all subsequent calls to the cursor methods must complete within the limit specified by the timeoutMS option. All documents must be returned within this limit. 游标生存期模式使用timeoutMS来限制游标的整个生存期。在此模式下,游标的初始化和对游标方法的所有后续调用必须在timeoutMS选项指定的限制内完成。所有文件必须在此限制内归还。Otherwise, the cursor's lifetime expires and a timeout error occurs.否则,游标的生存期将到期,并发生超时错误。

When you close a cursor by calling the toArray() or close() method, the timeout resets for the killCursors command to ensure server-side resources are cleaned up.当您通过调用toArray()close()方法关闭游标时,killCursors命令的超时会重置,以确保服务器端资源得到清理。

The following example shows how to set the timeoutMS option to ensure that the cursor is initialized and all documents are retrieved within 10 seconds:以下示例显示了如何设置timeoutMS选项,以确保游标初始化,并在10秒内检索到所有文档:

const docs = await collection.find({}, {timeoutMS: 10000}).toArray();

Cursor Iteration Mode游标迭代模式

The cursor iteration mode uses the timeoutMS option to limit each call to the next(), hasNext(), or tryNext() method. 游标迭代模式使用timeoutMS选项来限制对next()hasNext()tryNext()方法的每次调用。The timeout refreshes after each call completes. This is the default mode for all tailable cursors, such as the tailable cursors returned by the find() method on capped collections or change streams.每次调用完成后,超时时间都会刷新。这是所有可伸缩游标的默认模式,例如上限集合或更改流上find()方法返回的可伸缩游标。

The following code example iterates over documents in the mflix collection using a cursor with the timeoutMode set to iteration, and then fetches and logs the imdb_url for each movie document:以下代码示例使用timeoutMode设置为iteration(迭代)的游标迭代mflix集合中的文档,然后获取并记录每个电影文档的imdb_url

for await (const movie of mflix.find({}, { timeoutMode: 'iteration' })) {
const imdbResponse = await fetch(movie.imdb_url);
console.log(await imdbResponse.text());
}

API Documentation文档

To learn more about using timeouts with the Node.js driver, see the following API documentation:要了解有关使用Node.js驱动程序超时的更多信息,请参阅以下API文档: