【问题标题】:c - accessing value.type when iterating bsonc - 迭代 bson 时访问 value.type
【发布时间】:2015-02-17 16:32:39
【问题描述】:

我正在尝试遵循 libbson API 文档。但似乎我有什么问题。 documentation 声明您可以这样做:

const bson_value_t *value;

value = bson_iter_value (&iter);

if (value.type == BSON_TYPE_INT32) {
   printf ("%d\n", value.value.v_int32);
}

但是当我尝试用它编译实际代码时,我收到以下错误:

example1.c:34:64: error: request for member ‘type’ in something not a structure or union

这是实际的代码:

#include <bson.h>
#include <mongoc.h>
#include <stdio.h>


int
main (int   argc,
              char *argv[])
{
    mongoc_client_t *client;
    mongoc_collection_t *collection;
    mongoc_cursor_t *cursor;
    const bson_t *doc;
    const bson_value_t *value;
    bson_t *query;
    char *str;
    bson_iter_t iter;
    bson_type_t type;
    mongoc_init ();

    client = mongoc_client_new ("mongodb://localhost:27017/");
    collection = mongoc_client_get_collection (client, "test", "test");
    query = bson_new ();
    cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);

    while (mongoc_cursor_next (cursor, &doc)) {
            str = bson_as_json (doc, NULL);
            if (bson_iter_init (&iter, doc)) {
               while (bson_iter_next (&iter)) {
                     printf ("Found element key: \"%s\"\n", bson_iter_key (&iter));
                        type = bson_iter_type (&iter);
                        printf("type %d\n", (int)type);
                        value = bson_iter_value (&iter);
                        printf("Found values of type %d", value.type);
                     }
            }
            bson_free(str);
        }

    bson_destroy (query);
    mongoc_cursor_destroy (cursor);
    mongoc_collection_destroy (collection);
    mongoc_client_destroy (client);

    return 0;
}

【问题讨论】:

  • 文档有错字,应该是value-&gt;type
  • @immibis 你确定吗?当我尝试这个时,我得到:`example1.c|34 col 64 error| ‘bson_value_t’没有名为‘type’的成员`
  • ...应该是value-&gt;value_type。提交错误报告或其他内容。

标签: c mongodb struct bson mongo-c-driver


【解决方案1】:

value 是一个指针。您需要取消引用它:

value->type

(*value).type

此外,根据the documentationbson_value_t 没有名为type 的成员。也许他们的意思是

value->value_type

【讨论】:

  • 当我尝试这个时,我得到:`example1.c|34 col 64 error| ‘bson_value_t’没有名为‘type’的成员
  • @Oz123 很好,那么文档是错误的。但这修复了您发布的代码中的错误。
  • 是的,文档有误!应该是(*value).value_type);
猜你喜欢
  • 1970-01-01
  • 2020-02-04
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
相关资源
最近更新 更多