Trait mongod::Collection

source ·
pub trait Collection {
    const COLLECTION: &'static str;

    // Required methods
    fn from_document(document: Document) -> Result<Self, Error>
       where Self: Sized;
    fn into_document(self) -> Result<Document, Error>;
}
Expand description

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)
    }
}

Required Associated Constants§

source

const COLLECTION: &'static str

The name of the collection to store the documents in.

Required Methods§

source

fn from_document(document: Document) -> Result<Self, Error>
where Self: Sized,

Convert from a BSON Document into the Collections type.

source

fn into_document(self) -> Result<Document, Error>

Convert the Collections type into a BSON Document.

Object Safety§

This trait is not object safe.

Implementors§