16 releases (7 breaking)

Uses old Rust 2015

0.8.0 Jan 2, 2019
0.7.0 Dec 30, 2018
0.6.0 Dec 26, 2018
0.4.0 Aug 11, 2018
0.3.2 Jul 25, 2018

#124 in #mongo-db

Download history 5/week @ 2024-02-21 6/week @ 2024-02-28 1/week @ 2024-03-06 4/week @ 2024-03-13 5/week @ 2024-03-27 14/week @ 2024-04-03

56 downloads per month
Used in 2 crates

MIT license

774 lines

Magnet, a JSON schema generator

Magnet on crates.io Magnet on docs.rs Magnet Download Magnet License Lines of Code Twitter

These two related crates, magnet_derive and magnet_schema help you define (and, in most cases, automatically derive) MongoDB-flavored JSON schemas for your domain model types. Currently, the primary use case for this library is to make it easy to validate serializeable types when using Avocado or the MongoDB Rust driver.

The defined BsonSchema trait defines a single function, bson_schema, which should/will return a Bson Document that is a valid JSON schema describing the structure of the implementing type. Example:

extern crate serde_derive;
extern crate serde;
extern crate bson;
extern crate magnet_derive;
extern crate magnet_schema;
extern crate mongodb;

use std::collections::HashSet;
use magnet_schema::BsonSchema;

use mongodb::{ Client, ThreadedClient, CommandType };
use mongodb::db::{ ThreadedDatabase };

struct Person {
    name: String,
    nicknames: HashSet<String>,
    age: usize,
    contact: Option<Contact>,

#[derive(BsonSchema, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
enum Contact {

fn main() {
    let schema = Person::bson_schema();
    let spec = doc! {
        "create": "Person",
        "validator": { "$jsonSchema": schema },
    let client = Client::connect("localhost", 27017).expect("can't connect to mongod");
    let db = client.db("Example");
    db.command(spec, CommandType::CreateCollection, None).expect("network error");
    // etc.

For milestones and custom #[attributes], please see the documentation.

Release Notes


  • Implement BsonSchema for VecDeque, BinaryHeap, LinkedList, Range, RangeInclusive, and PhantomData
  • Add Eq + Hash and Ord bounds on map keys and set elements where appropriate


  • Upgrade uuid dependency to 0.7.1, and include v4 and serde features
  • Upgrade url dependency to 1.7.2


  • impl BsonSchema for arrays of size 2N between 128 and 65536; and sizes 1.5 * 2N between 96 and 1536.
  • Rewrite generics handling using syn::Generics::split_for_impl
  • Use scoped lints in magnet_schema as well


  • Handle generic types with default generic parameters correctly, by not including the defaults in the generated impl (which would result in a compiler error)
  • Use scoped lints for Clippy
  • Update some dependencies


  • Update bson to 0.13.0 and require its u2i feature. This version fixes a bug where unit struct were serialized as 1-element arrays. The u2i feature allows unsigned integers (within the appropriate range) to be serialized as signed integers.


  • Fix a bug where Option<enum> was not allowed to be null/None by the generated BSON schema
  • Remove an incorrect item from the documentation
  • Fix several Clippy lints
  • Update dependencies


  • impl BsonSchema for Document
  • impl BsonSchema for ObjectId
  • Documentation improvements
  • Update dependencies


  • Relax Display bound for HashMap/BTreeMap keys, use ToString instead
  • Update proc_macro2 dependency so that we can use TokenStream::default()


  • Remove #[magnet(rename = "...")] attribute
  • UnorderedDoc::eq(), assert_doc_eq! and assert_doc_ne! no longer clone their arguments
  • Update syn and quote dependencies
  • Improve documentation


  • Update bson dependency


  • Support for generic types


  • Unit tests and a test suite have been added.
  • Bug fix: Option::bson_schema() didn't handle the bsonType field, so Option<integer> wasn't allowed to be null. This has been corrected.
  • Bug fix: every generated schema now uses Bson::I64 for representing array lengths / collection counts
  • Enhancement: impl BsonSchema for { HashMap, BTreeMap } now has a less stringent trait bound on the key. It is now Display instead of AsRef<str>.


  • Add support for #[magnet(min_incl = "...", min_excl = "...", max_incl = "...", max_excl = "...")] attributes on struct fields (named as well as newtype and tuple)


  • Add support for enums, respecting Serde's tagging conventions (untagged/external/internal/adjacent), except newtype variants around other (inner) enums
  • Refactoring, code quality improvements


  • Add support for newtype structs and tuple structs
  • Respect #[serde(rename_all = "...")] and #[serde(rename = "...")] attributes
  • Add Serde-conform case conversion
  • Code formatting / organization and documentation improvements


  • Initial release, only regular structs with named fields are supported


~47K SLoC