I am developing a project using GridFS to save large files as binary blob into MongoDB; I am using C++ API;
So far I am able to save large files into bucket, which in mongosh gives me two collections fs.chunks and fs.files;
However, I have problems to delete files from the bucket. I tried to use the C++ API and below are the code snip I am using:
# code that successfully assign "doc" as bsoncxx::v_noabi::document::view&
bucket.delete_file(doc["_id"].get_oid().value.to_string());
or bucket.delete_file(doc["_id"].get_oid().value);
or even bucket.delete_file(doc["_id"].get_oid());
None of the above code allow me to compile my code, error message always says
error: no matching function for call to ‘mongocxx::v_noabi::gridfs::bucket::delete_file(bsoncxx::v_noabi::document::view&)’
or similar input type not match delete_file() input variable.
I looked the official document says that the delete_file() accept and input variable “id” can be the type of [bsoncxx::v_noabi::types::bson_value::view
which means anything in BSON;
But even I tried to convert the oid to a bson_value object does not fix the problem. I suspect there could be some bugs in the function? And I would like to seek help or advice from community. Thanks again.
You need to convert the _id field of your document to a bsoncxx::types::bson_value::view using the bsoncxx::types::bson_value::view_or_value constructor. I have shared sample code below.
// ---------------UPLOAD---------------//
// "sample_gridfs_file" is the name of the GridFS file stored on the server.
auto uploader = bucket.open_upload_stream("sample_gridfs_file");
// ASCII for "HelloWorld"
std::uint8_t bytes[10] = {72, 101, 108, 108, 111, 87, 111, 114, 108, 100};
// Write 50 bytes to the file.
for (auto i = 0; i < 5; ++i) {
uploader.write(bytes, 10);
}
auto result = uploader.close();
// // ---------------DELETE---------------//
// Delete the uploaded file by using the id.
// "id" can be reused directly, but construct a document for the sake of example.
bsoncxx::types::bson_value::view id = result.id();
bsoncxx::document::value doc_value = bsoncxx::builder::basic::make_document(bsoncxx::builder::basic::kvp("_id", id));
bsoncxx::document::view doc_view = doc_value.view();
bsoncxx::types::bson_value::view_or_value id_value {doc_view["_id"].get_value()};
// Pass the id to the delete_file
bucket.delete_file(id_value);