如何在 Mongoose 查询上设置超时? [英] How do I set a timeout on a Mongoose query?

查看:44
本文介绍了如何在 Mongoose 查询上设置超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Mongoose 和一个非常大的 Mongo 数据库,我希望像 MySet.find({}) 这样的昂贵查询在 10 秒后超时.

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);

我试过传递 maxTimeMS 选项到 find 函数,但这根本没有任何影响:

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) {});

有什么想法吗?

推荐答案

您可以使用 Query#maxTime 方法.

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) { ... });

您可以通过 mongoose.set('debug', true); 启用 Mongoose 调试来确认它是否正确设置了 maxTimeMS 选项,然后您将看到控制台输出对于这个查询,看起来像:

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: {} }

这篇关于如何在 Mongoose 查询上设置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆