乐闻世界logo
搜索文章和话题

How do I set a timeout on a Mongoose query?

1个答案

1

When using Mongoose (a MongoDB object modeling tool for Node.js) for database queries, you might want to set a timeout for the query, especially when dealing with queries that may run for an extended period or under high load. Setting a timeout helps prevent database operations from consuming resources for too long and can improve the responsiveness and stability of your application.

1. Using the maxTimeMS() Method

maxTimeMS() is a method of Mongoose queries that allows you to specify a maximum execution time (in milliseconds). If the query execution exceeds this limit, MongoDB attempts to terminate the query. This is a way to set a timeout at the query level.

javascript
const mongoose = require('mongoose'); const User = mongoose.model('User', new mongoose.Schema({ name: String })); async function findUser() { try { const result = await User.find({ name: 'Alice' }) .maxTimeMS(100) // Set maximum execution time to 100 milliseconds .exec(); console.log(result); } catch (error) { console.error('Query timeout or other error', error); } } findUser();

2. Using Connection String Options

When creating a database connection, you can also set socketTimeoutMS and connectTimeoutMS in the connection string. These settings affect all operations initiated through this connection.

  • socketTimeoutMS: This option sets the timeout for all MongoDB operations except for the connection.
  • connectTimeoutMS: This option sets the timeout for attempting to connect to MongoDB.
javascript
const mongoose = require('mongoose'); const connectionString = 'mongodb://localhost:27017/mydatabase?socketTimeoutMS=1000&connectTimeoutMS=1000'; // Set timeout to 1000 milliseconds mongoose.connect(connectionString, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Database connection successful')) .catch(err => console.error('Database connection failed', err)); // All operations through this connection will have these timeout settings

3. Using the options Property of Query

You can directly set maxTimeMS in the options property of the query, which is similar to using the maxTimeMS() method but configured differently.

javascript
const result = await User.find({}).setOptions({ maxTimeMS: 100 }).exec();

These methods can help you manage and control query timeouts when using Mongoose for database operations, thereby improving the performance and user experience of your application.

2024年6月29日 12:07 回复

你的答案