MongoDB Macro is a crate with macros for quickly creating structures when working with mongodb. In particular, macros are implemented for quick initialization of structures of the "factory" pattern. The purpose of this crate is to reduce the amount of boilerplate code when initializing standard structures.
Install using cargo:
cargo install mongodb-macro
Make sure you also add to the project:
mongodb = "*"
clap = { version = "*", features = ["derive", "env"] }
```rust
use mongodb::bson::Bson;
// env DBURL should contain a link to the mongodb url // env DBNAME should contain the database name // env COLLECTIONNAME should contain the collection name mongodbmacro::collection!(CollectionFactory; CollectionFactoryOpts); // or with a specified env // mongodbmacro::collection!(CollectionFactory; CollectionFactoryOpts; ("MONGODBURL", "MONGODBNAME", "MONGOCOLLECTION_NAME"));
async fn main() -> std::io::Result<()> {
let factory = CollectionFactory::parse();
let collection = factory.create::<Bson>().await.expect("failed to connect");
...
} ```
```rust
use mongodb::bson::Bson;
// env DBURL should contain a link to the mongodb url // env DBNAME should contain the database name mongodbmacro::database!(DbFactory; DbFactoryOpts); // or with a specified env // mongodbmacro::database!(DbFactory; DbFactoryOpts; ("MONGODBURL", "MONGODBNAME"));
async fn main() -> std::io::Result<()> {
let factory = DbFactory::parse();
let db = factory.create().await.expect("failed to connect");
let collection = db.collection::<Bson>("users");
...
} ```
```rust
use mongodb::bson::Bson;
// env DBURL should contain a link to the mongodb url mongodbmacro::client!(ClientFactory; ClientFactoryOpts); // or with a specified env // mongodbmacro::client!(ClientFactory; ClientFactoryOpts; "MONGODB_URL");
async fn main() -> std::io::Result<()> {
let factory = ClientFactory::parse();
let client = factory.create().await.expect("failed to connect");
let db = client.database("demo");
let collection = db.collection::<Bson>("users");
...
} ```
```rust
use mongodb::bson::Bson;
mongodbmacro::config!(Opts); // equivalent to // mongodbmacro::config!(Opts; "DBNAME", "COLLECTIONNAME", "DBURL"); // // or with prefix // // mongodbmacro::config!(Opts, "MONGO"); // equivalent to // mongodbmacro::config!(Opts; "MONGODBNAME", "MONGOCOLLECTIONNAME", "MONGODB_URL");
async fn main() -> std::io::Result<()> {
let opts = Opts::parse();
let client = mongodb::Client::with_uri_str(&opts.db_url).await.expect("failed to connect");
let db = client.database(&opts.db_name);
let collection = db.collection::<Bson>(&opts.collection_name);
...
} ```
Current version: 1.0.0
License: MIT