[][src]Macro mongodm::field

macro_rules! field {
    ( $field:ident in $type:path ) => { ... };
}

Statically check presence of field in a given struct and stringify it.

Note that it sadly won't work with #[serde(rename = "...")] and #[serde(rename_all = "...")].

Example

use mongodm::mongo::bson::doc;
use mongodm::field;
use mongodm::operator::*;

struct MyModel {
    foo: i64,
    bar: i64,
    lorem: String,
}

// Statically checked
let a = doc! {
    And: [
        { field!(foo in MyModel): { Exists: true } },
        {
            Or: [
                { field!(bar in MyModel): { GreaterThan: 100 } },
                { field!(lorem in MyModel): "ipsum" }
            ]
        }
    ]
};

// Hardcoded strings
let b = doc! {
    "$and": [
        { "foo": { "$exists": true } },
        {
            "$or": [
                { "bar": { "$gt": 100 } },
                { "lorem": "ipsum" }
            ]
        }
    ]
};

// Generated document are identicals
assert_eq!(a, b);

If the field doesn't exist, compilation will fail.

This example deliberately fails to compile
use mongodm::mongo::bson::doc;
use mongodm::field;
use mongodm::operator::*;

struct MyModel {
    bar: i64,
}

// Doesn't compile because `foo` isn't a member of `MyModel`
doc! { field!(foo in MyModel): 0 };