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
The following error message is:
the trait bound `Vec<user_model::User>: Extend<Result<user_model::User, mongodb::error::Error>>` is not satisfiednthe 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
2
Answers
Here is how I managed this in one of my projects.
I simply iterate over the cursor calling
next
and push each item in a vector. I used the Document type to collect the results.Using a match for each result allows to handle the errors properly, because extraction may fail.
Converting an element in the cursor to a
User
might fail. You may only collect into aVec
ofResult
with.collect()
.The easy way to get to
Vec<User>
here would be to use.try_collect()
. Just make sure to handle theErr
correctly and not just useunwrap
as I’ve done here.