Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a timeout on a Mongoose query?

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?

like image 493
Alex Henrie Avatar asked Mar 12 '15 07:03

Alex Henrie


People also ask

Why is Mongoose timing out?

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.

What is skip and limit in 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.

What does exec () do Mongoose?

In mongoose, exec method will execute the query and return a Promise.

Does Mongoose close connection automatically?

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.


2 Answers

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: {} }
like image 87
JohnnyHK Avatar answered Oct 20 '22 00:10

JohnnyHK


TL;DR:

MySet.find({ $query: { /*Query here*/ }, $maxTimeMS: 10000 });

You can test with this query :

MySet.find({ $query: {"$where": "sleep(100) || true"}, $maxTimeMS: 10000 });

Why it works:

You can use Query modifiers

And especialy this one : $maxTimeMS

Be careful : this operator is deprecated in mongo Shell since v3.2

like image 32
Yoluk Avatar answered Oct 19 '22 22:10

Yoluk