首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MongoDB BSON故障

MongoDB BSON故障
EN

Stack Overflow用户
提问于 2016-01-20 17:25:39
回答 1查看 1K关注 0票数 0

我使用MongoDB C库将文档插入到同一个数据库中的各种集合中,并且在调用BSON_APPEND_OID (doc、"_id“&_id)时反复获得引用的错误(以及可爱的查看错误);

我想在集合中使用相同的oid -这样每个集合中的每一个时间戳条目都有相同的oid,这就是我开始得到错误的时候。因此,我放弃了这一点,并尝试为每个条目创建新的OID,而我仍然得到相同的错误。

在第一个版本中,我试图重用OID:

代码语言:javascript
复制
int insert_mongo(char json[100], char *coll, mongoc_client_t *client, bson_oid_t oid){

    mongoc_collection_t *collection;
    bson_error_t error;
    bson_t *doc;

    collection = mongoc_client_get_collection (client, "edison", coll);     
    doc = bson_new_from_json((const uint8_t *)json, -1, &error);
    BSON_APPEND_OID (doc, "_id", &oid);
    if (!doc) {
        fprintf (stderr, "%s\n", error.message);
        return EXIT_FAILURE;
    }

    if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
        fprintf (stderr, "%s\n", error.message);
        return EXIT_FAILURE;
    }
    bson_destroy (doc);
    mongoc_collection_destroy (collection);
    return EXIT_SUCCESS;
}

在第2版中,我创建了一个新的OID:

代码语言:javascript
复制
int insert_mongo(char json[100], char *coll, mongoc_client_t *client){

    mongoc_collection_t *collection;
    bson_error_t error;
    bson_t *doc;
    bson_oid_t oid;

    bson_oid_init (&oid, NULL);
    collection = mongoc_client_get_collection (client, "edison", coll);
    doc = bson_new_from_json((const uint8_t *)json, -1, &error);
    BSON_APPEND_OID (doc, "_id", &oid);
    if (!doc) {
        fprintf (stderr, "%s\n", error.message);
        return EXIT_FAILURE;
    }

    if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
        fprintf (stderr, "%s\n", error.message);
        return EXIT_FAILURE;
    }
    bson_destroy (doc);
    mongoc_collection_destroy (collection);
    return EXIT_SUCCESS;
}

第二次用MongoDB bson_append_oid()调用函数时,这两个版本都有错误:前提条件失败: bson

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-20 18:15:34

猜测字符串不适合char[100],因此分段错误是在doc = bson_new_from_json((const uint8_t *)json, -1, &error);生成的。我可以想象,由于启用了自动字符串长度检测(第二个参数,-1),函数将在char[100]之后继续读取内存,因为它找不到不适合缓冲区的字符串的结尾。

要解决这种可能性,请将-1替换为100 (即缓冲区的大小),并查看现在是否存在错误消息而不是分段错误。

编辑:扩展这个想法,也可能是bson_new_from_json失败,因此doc仍然是NULL,在下一行中,您尝试将OID附加到NULL,这可能会产生分段错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34906576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档