Databases
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"
| Feature | Module | Notes |
|---|---|---|
bson-2 | vld_data::bson2 | bson 2.x |
bson-3 | vld_data::bson3 | bson 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 aDocument, validate the document againstS, return it.from_document::<S, T>(doc)— validate againstS, then deserialize intoT.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):
| BSON | JSON the schema sees |
|---|---|
string, boolean, null, Int32, Int64, finite Double | the 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, timestamp | their $-keyed forms ({"$numberDecimal": ".."}, …) |
Map a $-key with as "$oid" / as "$date" in a nested schema, as in the example.
Gotchas
to_documentvalidates the document, not the value:ObjectIdfields are checked as{"$oid": ..}, so a schema written for a hexStringfield rejects them.- Dates before 1970 or after 9999 are not ISO strings in relaxed Extended JSON; a schema with
iso_datetime()rejects them. from_documentvalidates before deserializing: a document that passes the schema can still fail to deserialize intoT(Deserialization).- bson 2 turns on serde_json's
preserve_orderfeature, and Cargo enables a feature for the whole build: withbson-2, everyserde_jsonmap 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.