mongodb_gridfs/bucket/
rename.rs1use crate::bucket::GridFSBucket;
2use bson::{doc, oid::ObjectId, Document};
3use mongodb::{error::Result, options::UpdateOptions, results::UpdateResult};
4
5impl GridFSBucket {
6 pub async fn rename(&self, id: ObjectId, new_filename: &str) -> Result<UpdateResult> {
12 let dboptions = self.options.clone().unwrap_or_default();
13 let bucket_name = dboptions.bucket_name;
14 let file_collection = bucket_name + ".files";
15 let files = self.db.collection::<Document>(&file_collection);
16
17 let update_options = UpdateOptions::builder()
18 .write_concern(dboptions.write_concern)
19 .build();
20
21 files
22 .update_one(
23 doc! {"_id":id},
24 doc! {"$set":{"filename":new_filename}},
25 update_options,
26 )
27 .await
28 }
29}
30
31#[cfg(test)]
32mod tests {
33 use super::GridFSBucket;
34 use crate::{options::GridFSBucketOptions, GridFSError};
35 use bson::doc;
36 use bson::Document;
37 use mongodb::Client;
38 use mongodb::Database;
39 use uuid::Uuid;
40 fn db_name_new() -> String {
41 "test_".to_owned()
42 + Uuid::new_v4()
43 .hyphenated()
44 .encode_lower(&mut Uuid::encode_buffer())
45 }
46
47 #[tokio::test]
48 async fn rename_a_file() -> Result<(), GridFSError> {
49 let client = Client::with_uri_str(
50 &std::env::var("MONGO_URI").unwrap_or("mongodb://localhost:27017/".to_string()),
51 )
52 .await?;
53 let dbname = db_name_new();
54 let db: Database = client.database(&dbname);
55 let bucket = &GridFSBucket::new(db.clone(), Some(GridFSBucketOptions::default()));
56 let id = bucket
57 .clone()
58 .upload_from_stream("test.txt", "test data".as_bytes(), None)
59 .await?;
60
61 assert_eq!(id.to_hex(), id.to_hex());
62
63 bucket.rename(id, "renamed_file.txt").await?;
64
65 let file = db
66 .collection::<Document>("fs.files")
67 .find_one(doc! { "_id": id }, None)
68 .await?
69 .unwrap();
70 assert_eq!(file.get_str("filename").unwrap(), "renamed_file.txt");
71
72 db.drop(None).await?;
73 Ok(())
74 }
75}