Databases

MongoDB (bson)

Validate BSON documents before insert and after find, with bson 2 or 3 and any MongoDB driver.

vld_data::bson3 validates bson::Documents with vld schemas: to_document before insert_one / replace_one, from_document / validate_document after find. It depends on bson only, not on the mongodb driver (mongodb 3 works with bson 2 and 3).

Install

Cargo.toml
[dependencies]
vld = "0.8"
vld-data = { version = "0.8", features = ["bson-3"] }
bson = "3"
FeatureModuleNotes
bson-2vld_data::bson2bson 2.x
bson-3vld_data::bson3bson 3.x (enables its serde and serde_json-1 features)

The modules have the same API and can be enabled together. Your bson dependency must be the major of the module you use. The examples use bson3.

Example

use bson::{doc, oid::ObjectId, DateTime};
use vld_data::bson3::prelude::*;

// An ObjectId is {"$oid": "<24 hex>"}, a date {"$date": "<ISO 8601>"}.
vld::schema! {
    #[derive(Debug)]
    pub struct ObjectIdSchema {
        pub oid: String as "$oid" => vld::string().len(24),
    }
}

vld::schema! {
    #[derive(Debug)]
    pub struct DateSchema {
        pub date: String as "$date" => vld::string().iso_datetime(),
    }
}

vld::schema! {
    #[derive(Debug)]
    pub struct UserSchema {
        pub id: ObjectIdSchema as "_id" => vld::nested!(ObjectIdSchema),
        pub name: String => vld::string().min(1),
        pub joined: DateSchema => vld::nested!(DateSchema),
    }
}

#[derive(serde::Serialize, serde::Deserialize)]
struct User {
    #[serde(rename = "_id")]
    id: ObjectId,
    name: String,
    joined: DateTime,
}

let user = User { id: ObjectId::new(), name: "Ada".into(), joined: DateTime::now() };
let doc = to_document::<UserSchema, _>(&user)?;      // collection.insert_one(doc)

let back: User = from_document::<UserSchema, _>(doc)?; // after find_one

let bad = doc! { "_id": "not-an-oid", "name": "", "joined": DateTime::now() };
assert!(validate_document::<UserSchema>(&bad).is_err());

API

  • to_document::<S, T>(&value) — serialize to a Document, validate the document against S, return it.
  • from_document::<S, T>(doc) — validate against S, then deserialize into T.
  • validate_document::<S>(&doc) — validate and return the parsed schema value.
  • validate_documents::<S>(&[doc]) — the index and error of the first invalid document.
  • VldBsonError — Validation, Serialization, Deserialization.

How documents look to a schema

The schema sees relaxed Extended JSON (Bson::into_relaxed_extjson):

BSONJSON the schema sees
string, boolean, null, Int32, Int64, finite Doublethe plain JSON value
ObjectId{"$oid": "65a1b2c3d4e5f60718293a4b"}
DateTime (years 1970–9999){"$date": "2023-11-14T22:13:20Z"}
DateTime (other years){"$date": {"$numberLong": "-1"}}
Decimal128, Binary, NaN / ±inf, regex, timestamptheir $-keyed forms ({"$numberDecimal": ".."}, …)

Map a $-key with as "$oid" / as "$date" in a nested schema, as in the example.

Gotchas

  • to_document validates the document, not the value: ObjectId fields are checked as {"$oid": ..}, so a schema written for a hex String field rejects them.
  • Dates before 1970 or after 9999 are not ISO strings in relaxed Extended JSON; a schema with iso_datetime() rejects them.
  • from_document validates before deserializing: a document that passes the schema can still fail to deserialize into T (Deserialization).
  • bson 2 turns on serde_json's preserve_order feature, and Cargo enables a feature for the whole build: with bson-2, every serde_json map in your application keeps insertion order instead of sorting keys (serialized JSON key order changes; equality does not). vld itself does not depend on map order. bson 3 does not do this.