Trait mongod::Collection [−][src]
Used to create a mongo collection from a type.
This trait can be thought of as a collection's name along with its schema.
This trait is required in order to intract with the mongo Client
. The
implementation is used to tie a collection name to the chosen type while also defining how to
convert to and from a BSON Document
.
Examples
Defining a struct as a mongo document.
use std::convert::TryFrom; use mongod::bson::{self, Document}; use mongod::{Collection, Error}; use mongod::ext; pub struct User { pub name: String, } impl Collection for User { const COLLECTION: &'static str = "users"; fn from_document(document: Document) -> Result<Self, Error> { let mut document = document; let mut name: Option<String> = None; if let Some(value) = document.remove("name") { name = Some(String::try_from(ext::bson::Bson(value))?); } if name.is_none() { return Err(Error::invalid_document("missing required fields")); } Ok(Self { name: name.expect("could not get name"), }) } fn into_document(self) -> Result<Document, Error> { let mut doc = Document::new(); doc.insert("name", self.name); Ok(doc) } }
Associated Constants
const COLLECTION: &'static str
[src]
The name of the collection to store the documents in.
Required methods
fn from_document(document: Document) -> Result<Self, Error> where
Self: Sized,
[src]
Self: Sized,
Convert from a BSON Document
into the Collection
s type.
fn into_document(self) -> Result<Document, Error>
[src]
Convert the Collection
s type into a BSON Document
.