Convert Struct with vector into Document MongoDB

hi everyone,
i'm try convert a struct to mongodb Document, but i have a field Vector inside, and i get a error when i try convert:
Then i created this little example, and i continue get the same error message.
Somebody can help-me?

  let vec1 = vec!( "a","b","c");
  let doc = doc!{ "vector" : (&vec1) };

let doc = doc!{ "vector" : (&vec1) };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait std::convert::From<&std::vec::Vec<&str>> is not implemented for mongodb::Bson

I've noticed that the bson library seems to need ownership of some variables to do the conversion. There may just be a blanket impl missing in the library. Probably worth an upstream pr. In the meantime, try cloning your vec, and storing that in the struct.

I tried clone, copy, but don't work.
Stranger than a new vector empty is created without error.

      let doc = doc!{ "vector" : vec!( ) };  // it's work
let doc = doc!{ "vector" : vec1 };


let doc = doc!{ "vector" : vec1.clone() };

should work.

Don't work. unfortunately

error[E0277]: the trait bound mongodb::Bson: std::convert::From<std::vec::Vec<std::string::String>> is not satisfied
--> src\paciente\
113 | let doc1 = doc!{ "vector" : _vec1.clone() };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait std::convert::From<std::vec::Vec<std::string::String>> is not implemented for mongodb::Bson
= help: the following implementations were found:
<mongodb::Bson as std::convert::From<&'a std::string::String>>
<mongodb::Bson as std::convert::From<&'a str>>
<mongodb::Bson as std::convert::From<(mongodb::spec::BinarySubtype, std::vec::Vec)>>
<mongodb::Bson as std::convert::From<(std::string::String, mongodb::ordered::OrderedDocument)>>
and 16 others
= note: required by std::convert::From::from
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

Ah okay, in that case you should probably convert each individual item in the vector to a Bson:

let doc = doc!{
    "vector": vec1.into_iter().map(Bson::from).collect::<Vec<_>>()

But you could just look at the documentation of the bson crate and the Bson type and see for what types Bson::from is implemented.

1 Like

it's worked.
Very thanks, you saved my day.
i'm in process of assimilation of the language.