0

我正在使用 MongoDB C 库将文档插入到同一数据库中的各种集合中,并且在调用 BSON_APPEND_OID (doc, "_id", &oid);

曾想跨集合使用相同的 oid——这样每个集合中的每个带时间戳的条目都将具有相同的 oid,这就是我开始收到错误的时候。所以我放弃了这一点,并尝试为每个条目创建新的 OID,但我仍然遇到同样的错误。

我尝试重用 OID 的版本一:

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

以及我创建新 OID 的版本 2:

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

4

1 回答 1

1

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

要解决这种可能性,请替换-1100(即缓冲区的大小)并查看是否有错误消息而不是现在的段错误。
编辑:扩展这个想法,也可能是bson_new_from_json失败,因此doc仍然是NULL并且在下一行中您尝试将 OID 附加到NULL,这可能会产生段错误。

于 2016-01-20T18:15:34.733 回答