我正在使用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, "%sn", error.message);
return EXIT_FAILURE;
}
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
fprintf (stderr, "%sn", error.message);
return EXIT_FAILURE;
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
return EXIT_SUCCESS;
}
在版本 2 中,我创建了一个新的 OID:
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, "%sn", error.message);
return EXIT_FAILURE;
}
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
fprintf (stderr, "%sn", error.message);
return EXIT_FAILURE;
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
return EXIT_SUCCESS;
}
两个版本在第二次调用函数时都出错MongoDB bson_append_oid(): 前提条件失败: bson
我猜你的 JSON 字符串不适合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,这可能会产生段错误。