调用mongoc_collection_find函数时如何出错?

问题描述

查看 Mongo C driver 中用于对集合进行操作的函数,我看到它们中的许多使用 bson_error_t* 返回参数来获取可能的错误(并且它们返回 false那种情况)。

例如mongo_collection_insert

布尔

mongoc_collection_insert (mongoc_collection_t *collection,mongoc_insert_flags_t flags,const bson_t *document,const mongoc_write_concern_t *write_concern,bson_error_t *error);

其他(mongoc_collection_updatemongoc_collection_remove)的工作方式相同。

但是,执行查询函数 (mongoc_collection_find) 具有以下签名:

mongoc_cursor_t *
mongoc_collection_find (mongoc_collection_t *collection,mongoc_query_flags_t flags,uint32_t skip,uint32_t limit,uint32_t batch_size,const bson_t *query,const bson_t *fields,const mongoc_read_prefs_t *read_prefs)

这种情况下没有bson_error_t*参数,那么潜在的错误是如何返回的?

我认为可能检查返回值 NULL-ness 可能意味着错误(尽管根据文档返回值是“新分配的 mongoc_cursor_t 应在不再使用时使用 mongoc_cursor_destroy() 释放”

em> 并且他们没有提到在失败的情况下为 NULL 的可能性)但即使在这种情况下,如何知道发生了哪个确切的错误

解决方法

操作 mongoc_collection_aggregatemongoc_collection_find 非常相似,那里的文档说:

此函数返回一个新分配的 mongoc_cursor_t,当不再使用时,应使用 mongoc_cursor_destroy() 释放该 mongoc_cursor_t。返回的 NULL 永远不会是 bson_error_t;如果参数无效,则填写mongoc_cursor_t中的mongoc_cursor_t,并在选择服务器之前返回mongoc_cursor_next()。用户必须对返回的 mongoc_cursor_t 调用 mongoc_collection_find 才能执行聚合管道。

所以问题可能在于 if 不完整,但它的工作方式相同。

我提出了一个 modification to Mongo C driver documentation 来证实我的假设。