1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use crate::{bucket::GridFSBucket, options::GridFSFindOptions};
use bson::Document;
use mongodb::error::Result;
use mongodb::options::FindOptions;
use mongodb::Cursor;

impl GridFSBucket {
    /**
    Find and return the files collection documents that match @filter.
    [Spec](https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst#generic-find-on-files-collection)

    # Examples

    ```rust
    use bson::doc;
    # #[cfg(feature = "async-std-runtime")]
    # use futures::stream::StreamExt;
    # #[cfg(any(feature = "default", feature = "tokio-runtime"))]
    use tokio_stream::StreamExt;
    # use mongodb::error::Result;
    # use mongodb::Client;
    # use mongodb::Database;
    use mongodb_gridfs::{bucket::GridFSBucket, options::GridFSFindOptions};
    # use mongodb_gridfs::options::GridFSBucketOptions;

    # #[tokio::main]
    # async fn main() -> Result<()> {
    #    let client = Client::with_uri_str(
    #        &std::env::var("MONGO_URI").unwrap_or("mongodb://localhost:27017/".to_string()),
    #    )
    #    .await?;
    #    let db: Database = client.database("test");
    #    let bucket = &GridFSBucket::new(db.clone(), Some(GridFSBucketOptions::default()));
    let mut cursor = bucket
            .find(doc! {"filename":"test.txt"}, GridFSFindOptions::default())
            .await?;

        while let Some(_doc) = cursor.next().await {
            // ...
        }
    #    Ok(())
    # }
    ```
     */
    pub async fn find(
        &self,
        filter: Document,
        options: GridFSFindOptions,
    ) -> Result<Cursor<Document>> {
        let dboptions = self.options.clone().unwrap_or_default();
        let bucket_name = dboptions.bucket_name;
        let file_collection = bucket_name + ".files";
        let files = self.db.collection::<Document>(&file_collection);

        let find_options = FindOptions::builder()
            .allow_disk_use(options.allow_disk_use)
            .limit(options.limit)
            .max_time(options.max_time)
            .no_cursor_timeout(options.no_cursor_timeout)
            .skip(options.skip)
            .sort(options.sort)
            .read_concern(dboptions.read_concern)
            .build();

        files.find(filter, find_options).await
    }
}

#[cfg(test)]
mod tests {
    use super::GridFSBucket;
    use crate::{
        options::{GridFSBucketOptions, GridFSFindOptions},
        GridFSError,
    };
    use bson::doc;
    #[cfg(feature = "async-std-runtime")]
    use futures::stream::StreamExt;
    use mongodb::{Client, Database};
    #[cfg(any(feature = "default", feature = "tokio-runtime"))]
    use tokio_stream::StreamExt;
    use uuid::Uuid;

    fn db_name_new() -> String {
        "test_".to_owned()
            + Uuid::new_v4()
                .to_hyphenated()
                .encode_lower(&mut Uuid::encode_buffer())
    }

    #[tokio::test]
    async fn find_a_file() -> Result<(), GridFSError> {
        let client = Client::with_uri_str(
            &std::env::var("MONGO_URI").unwrap_or("mongodb://localhost:27017/".to_string()),
        )
        .await?;
        let dbname = db_name_new();
        let db: Database = client.database(&dbname);
        let bucket = &GridFSBucket::new(db.clone(), Some(GridFSBucketOptions::default()));
        let id = bucket
            .clone()
            .upload_from_stream("test.txt", "test data".as_bytes(), None)
            .await?;

        assert_eq!(id.to_hex(), id.to_hex());

        let mut cursor = bucket
            .find(doc! {"filename":"test.txt"}, GridFSFindOptions::default())
            .await?;

        while let Some(doc) = cursor.next().await {
            let doc = doc.unwrap();
            assert_eq!(doc.get_str("filename").unwrap(), "test.txt");
            assert_eq!(doc.get_i32("chunkSize").unwrap(), 261120);
            assert_eq!(doc.get_i64("length").unwrap(), 9);
            assert_eq!(
                doc.get_str("md5").unwrap(),
                "eb733a00c0c9d336e65691a37ab54293"
            );
        }
        db.drop(None).await?;
        Ok(())
    }

    #[tokio::test]
    async fn find_a_non_existing_file() -> Result<(), GridFSError> {
        let client = Client::with_uri_str(
            &std::env::var("MONGO_URI").unwrap_or("mongodb://localhost:27017/".to_string()),
        )
        .await?;
        let dbname = db_name_new();
        let db: Database = client.database(&dbname);
        let bucket = &GridFSBucket::new(db.clone(), Some(GridFSBucketOptions::default()));
        let id = bucket
            .clone()
            .upload_from_stream("test.txt", "test data".as_bytes(), None)
            .await?;

        assert_eq!(id.to_hex(), id.to_hex());

        let mut cursor = bucket
            .find(doc! {"filename":"null.txt"}, GridFSFindOptions::default())
            .await?;

        match cursor.next().await {
            None => assert!(true),
            Some(_) => assert!(false),
        }

        db.drop(None).await?;
        Ok(())
    }
}