WithSecureLabs / mongo-rs

A higher-level wrapper on top of the official bson & mongodb crates.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Return actual type instead of document with `Client::find`

dariusc93 opened this issue · comments

I feel that when Client::find is used that it should return the iterator with the actual type instead of the document. This could be a wrapper around the cursor (maybe similar to how wither does it) or maybe just have it converted into a vector. This should give a more high level feel to the crate since they wouldnt have to convert the document to the type in used with Collection::from_document manually and if they need it they could do it manually. What are your thoughts on it?

Are you thinking of something more like this?

use futures::stream::StreamExt;

use mongod::Collection;

let client = mongod::Client::new();

let mut cursor = client.find::<User, _>(None).await.unwrap();
while let Some(res) = cursor.next().await {
    if let Ok(user) = res {
        println!("{:?}", user);
    }
}

It makes sense to me, its going to be very rare that someone would want the document in raw form. TBH the only reason it is as it is now is because it returns the mongodb::Cursor. But I think you are right, we should wrap it to remove this unnecessary step. Let me see what I can do.

Have addressed this with the commit above.

Upon reflection I changed my mind on this, went for the following approach, as this then allows for us to do this:

use futures::stream::StreamExt;

use mongod::{Collection, TypedCursor};

let client = mongod::Client::new();

let cursor = client.find::<User, _>(None).await.unwrap();
let mut cursor: TypedCursor<User>::from(cursor);
while let Some(res) = cursor.next().await {
    if let Ok(user) = res {
        println!("{:?}", user);
    }
}

But looking at it now I guess the only benefit of this is we can more easily interact with the Document to get things like _id, maybe we should just wrap so we can get that out and force the typed cursor by default? I will have a further play.

Okay finally settled on an approach and have released 0.3.0:

let mut cursor = client.find::<User, _>(None).await.unwrap();
  while let Some(res) = cursor.next().await {
      if let Ok((id, user)) = res {
          println!("{} - {:?}", id, user);
      }
  }