4.7.1 => 4.7.2 : MongoError connection timed out
Problem
When testing mongoose@4.7.2 / mongodb@2.2.12, I get: > MongoError: connection 2 to XXXXXX timed out > at Function.MongoError.create (/node_modules/mongodb-core/lib/error.js:29:11) > at Socket.<anonymous> (/node_modules/mongodb-core/lib/connection/connection.js:186:20) > at Socket.g (events.js:286:16) > at emitNone (events.js:86:13) > at Socket.emit (events.js:185:7) > at Socket._onTimeout (net.js:333:8) > at tryOnTimeout (timers.js:224:11) > at Timer.listOnTimeout (timers.js:198:5)' } 'connection 2 to XXXXXX timed out this does not happen with mongoose@4.7.1 / mongodb@2.2.11. More details: - query: aggregate with allowDiskUse(true).read('secondaryPreferred').cursor() - timing: the error happens about 35s after sending the query (before first results are received) - node version: v6.3.0 - npm version: 3.10.9 - connect options: [code block] - query: [code block]
Error Output
Error: connection 2 to XXXXXX timed out
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Increase Connection Timeout for Mongoose and MongoDB
The connection timeout error occurs due to the default timeout settings in the MongoDB driver being insufficient for the aggregate query with allowDiskUse and read preferences. The query takes longer than the default timeout period, leading to a timeout error.
Awaiting Verification
Be the first to verify this fix
- 1
Update Connection Options
Modify the connection options to increase the timeout settings for the MongoDB connection. This can be done by specifying the 'socketTimeoutMS' and 'connectTimeoutMS' options in the connection string.
javascriptmongoose.connect('mongodb://localhost:27017/mydatabase', { socketTimeoutMS: 60000, connectTimeoutMS: 60000 }); - 2
Test the Connection
After updating the connection options, run the same aggregate query again to check if the timeout issue persists. Ensure that the query is executed under the same conditions as before.
javascriptconst results = await MyModel.aggregate([...]).allowDiskUse(true).read('secondaryPreferred').cursor(); - 3
Monitor Performance
Use MongoDB monitoring tools or logging to observe the performance of the query and connection. Ensure that the query completes successfully without timing out.
javascriptdb.currentOp(); - 4
Review MongoDB Logs
Check the MongoDB server logs for any additional errors or warnings that may indicate underlying issues with the server or network connectivity.
bashtail -f /var/log/mongodb/mongod.log
Validation
Confirm that the aggregate query completes successfully without throwing a timeout error. Additionally, monitor the execution time to ensure it is within acceptable limits.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep