我正在使用official Perl driver来处理mongodb。要捕获和处理错误,tez
和Try::Tiny
模块为recommended。但是,它没有按预期工作。请检查下面的代码应该根据文档工作,但事实上它不起作用:
Safe::Isa
根据文档自动建立连接,use MongoDB;
use Try::Tiny;
use Safe::Isa;
my $client;
try {
$client = MongoDB->connect('mongodb://localhost');
$client->connect;
} catch {
warn "caught error: $_";
};
my $collection = $client->ns('foo.bar');
try {
my $all = $collection->find;
} catch {
warn "2 - caught error: $_";;
};
上不会有例外。但是请求也没有例外!我还将connect()
字符串添加到force连接,但同样没有例外。我在没有安装mongodb的机器上运行此脚本,并且没有运行mongodb docker容器,因此必须出现异常。
有人可以解释我做错了什么吗?
答案 0 :(得分:1)
这是一个微妙的问题。 Note, a MongoDB::Cursor object holds the query and does not issue the
query to the server until the `result` method is called on it or until
an iterator method like `next` is called.
返回一个游标对象,但不会立即发出查询。来自MongoDB::Collection的文档:
mget