bson_comp
Stop fighting the doc! macro. Make your types generic-compatible.
If you work with MongoDB in Rust, you've definitely hit this wall. You have a nice, strongly-typed Enum or Struct, and you just want to use it in a query.
The Problem
You try to do this:
let filter = doc! ;
And the compiler screams at you with Error E0277:
the trait bound Bson: std::convert::From<Role> is not satisfied
required for Role to implement Into<Bson>
So you end up writing this boilerplate everywhere:
// ❌ The Ugly Way
// Manual conversion every time you use it.
let filter = doc! ;
The Solution
bson_comp (BSON Compatibility) handles that boilerplate for you. It implements Into<Bson> for your types so they fit right into the doc! macro.
// ✅ The Clean Way
let filter = doc! ;
Installation
Add this to your Cargo.toml:
[]
= "0.1"
= { = "1.0", = ["derive"] }
How to use it
1. For Enums (The most common use case)
Perfect for status flags, user roles, or category types.
use ;
use BsonComp;
use doc;
// Optional: controls how it looks in Mongo
2. For Structs
Useful when embedding objects inside other documents.
use Serialize;
use BsonComp;
use doc;
How it works
Rust's "Orphan Rules" prevent you from implementing From<YourType> for Bson because you don't own the bson crate.
However, the doc! macro accepts anything that implements Into<Bson>. Since Into is a generic trait, you are allowed to implement it for your own types.
This macro simply generates:
Requirements
- Your type must derive
serde::Serialize. - It panics if serialization fails (which shouldn't happen for standard Enums/Structs unless you have custom serialization logic that fails).
License
MIT. Enjoy clean code.