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 socket timeout on my connection, but the server crashes if the timeout is exceeded:
var options = {server: {socketOptions: {socketTimeoutMS: 10000}}};
var conn = mongoose.connect('mongodb://localhost/my_db', options);
I've tried passing the maxTimeMS option to the find function, but that doesn't have any effect at all:
MySet.find({}, {}, {timeout: true, maxTimeMS: 10000}, function(err, doc) {});
Any ideas?
This error happens because you're trying to use a model whose connection hasn't connected to MongoDB. Remember that, in Mongoose, every model has exactly one connection to MongoDB. The buffering timeout is usually due to either registering models on a newly created connection but using mongoose.
The limit method will be used to return the maximum number of results from the collection, while the skip method is used to skip the number of documents from the collection in MongoDB. If we have one collection name as a student, student collection contains a hundred documents in it.
In mongoose, exec method will execute the query and return a Promise.
You do need to call mongoose. disconnect() to close the connection, but you also need to wait until all save calls have completed their async work (i.e. called their callback) before doing that.
You can do this with the Query#maxTime
method.
So in your case, you would call it as:
MySet.find({}).maxTime(10000).exec(function(err, doc) { ... });
You can confirm it's correctly setting the maxTimeMS
option by enabling Mongoose debugging via mongoose.set('debug', true);
and then you'll see console output for this query that looks like:
Mongoose: myset.find({}) { maxTimeMS: 10000, safe: true, fields: {} }
MySet.find({ $query: { /*Query here*/ }, $maxTimeMS: 10000 });
You can test with this query :
MySet.find({ $query: {"$where": "sleep(100) || true"}, $maxTimeMS: 10000 });
You can use Query modifiers
And especialy this one : $maxTimeMS
Be careful : this operator is deprecated in mongo Shell since v3.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With