我正在使用 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;
}
在版本 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, "%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
最佳答案
我猜测您的 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,这可能会产生段错误。
关于c - MongoDB BSON OID 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34906576/