Search code examples
mongodbrustasync-awaitdatabase-cursor

How to collect mongodb::Cursor into a Vec in rust


I'm trying to use the .find() method in mongodb. The output yeilds a mongodb::Cursor. I'm unable to convert the cursor into a vector so that I can wrap them in a json and send it to my front-end. This is the following idea I've tried

enter image description here

The following error message is:

the trait bound `Vec<user_model::User>: Extend<Result<user_model::User, mongodb::error::Error>>` is not satisfied\nthe following other types implement trait `Extend<A>`

I've already included and use futures::StreamExt; and use futures::TryFutureExt; and tried out .try_next() and .map() instead of .collect(), still cant parse it


Solution

  • Converting an element in the cursor to a User might fail. You may only collect into a Vec of Result with .collect().

    let serial: Vec<Result<User, _>> = users.collect().await;
    

    The easy way to get to Vec<User> here would be to use .try_collect(). Just make sure to handle the Err correctly and not just use unwrap as I've done here.

    let serial: Vec<User> = users.try_collect().await.unwrap();