Derive Macro mongod_derive::Bson

source ·
#[derive(Bson)]
{
    // Attributes available to this derive:
    #[bson]
}
Expand description

Derives implementations for TryFrom so that the decorated type can be converted to & from BSON.

§Container Attributes

  • #[bson(from)]: derives TryFrom on Bson for type
  • #[bson(into)]: derives TryFrom on type for Bson

§#[bson(from)]

Tells the derive to only implement the from parts of the derive, i.e. deserialising only.

use std::convert::TryFrom;

#[derive(Debug, Bson)]
#[bson(from)]
struct User {
    name: String,
}
let mut doc = mongod::bson::Document::new();
doc.insert("name", "foo".to_owned());
let bson = mongod::bson::Bson::Document(doc);

let user = User::try_from(bson).unwrap();

println!("{:?}", user);

§#[bson(into)]

Tells the derive to only implement the into parts of the derive, i.e. serialising only.

use std::convert::TryFrom;

#[derive(Bson)]
#[bson(into)]
struct User {
    name: String,
}

let user = User { name: "foo".to_owned() };

let bson = mongod::bson::Bson::try_from(user).unwrap();

println!("{:?}", bson);

§Field Attributes

  • #[bson(serde)]

§#[bson(serde)]

Tells the derive to use serde for the decorated field.

use std::convert::TryFrom;

#[derive(Bson)]
struct User {
    name: String,
    #[bson(serde)]
    age: u32,
}

let user = User { name: "foo".to_owned(), age: 0 };

let bson = mongod::bson::Bson::try_from(user).unwrap();

println!("{:?}", bson);