I am using Mongoose with a very large Mongo database, and I want costly queries like MySet.find({}) to time out after 10 seconds.
I\'ve tried setting a
I finally got it working. First I prevent the server from crashing when the socket (i.e. a query) times out:
//don't crash the server if a query times out
mongoose.connection.on('error', function() {});
Then, every time I want to query the database, I disconnect from and reconnect to the database, setting socketTimeoutMS to 10000:
mongoose.disconnect();
mongoose.connect('mongodb://localhost/my_db', {
  server: {socketOptions: {socketTimeoutMS: 10000}}
});
MySet.find({}, function(err, doc) {});
This cuts off the query after precisely 10 seconds of execution.