我使用MongoDB C库将文档插入到同一个数据库中的各种集合中,并且在调用BSON_APPEND_OID (doc、"_id“&_id)时反复获得引用的错误(以及可爱的查看错误);
我想在集合中使用相同的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
发布于 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,这可能会产生分段错误。
https://stackoverflow.com/questions/34906576
复制相似问题