How do I set a timeout on a Mongoose query?

前端 未结 5 777
刺人心
刺人心 2020-12-19 01:48

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

5条回答
  •  Happy的楠姐
    2020-12-19 02:47

    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.

提交回复
热议问题