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 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
CodePudding user response:
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();
CodePudding user response:
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.
let mut results: Vec<Document> = Vec::new();
while let Some(result) = cursor.next().await {
match result {
Ok(document) => {
results.push(document);
}
_ => {
return HttpResponse::InternalServerError().finish();
}
}
}