thedodd / wither

An ODM for MongoDB built on the official MongoDB Rust driver.
https://docs.rs/wither
Other
324 stars 40 forks source link

Nice way to collect a cursor? #77

Closed wbrickner closed 3 years ago

wbrickner commented 3 years ago

Hello, it's me again 🤪.

What I've been doing to fetch many matching documents is I use the ::find method and then collect those one at a time manually, and I would suspect there's a cleaner way built in to wither.

collect_cursor

Is this at least correct? I may be mishandling the stream of Option<Result<Model, WitherError>>.

thedodd commented 3 years ago

Hey there. A few things to keep in mind:

That said, all of the work is taken care of and we get the added bonus of easy error handling. So your above code could be refined down to:

use futures::prelude::*;
let cursor = Model::find(&db, filter, opts).await?;
let models: Vec<_> = cursor.try_collect().await?; // Gives you a `Vec<M>` just like your image above.

This will propagate an error if creating the cursor fails, but will also propagate an error if an error takes place while streaming over the cursor. The propagated error type in this case will always be a WitherError.

wbrickner commented 3 years ago

That is nicer, thank you!