January 2019
Intermediate to advanced
520 pages
14h 32m
English
Since we have a declared structure, we can add functions to work with databases. The first function we will add is add_activity which adds an activity record to a database:
fn add_activity(conn: &Database, activity: Activity) -> Result<(), Error> { let doc = doc! { "user_id": activity.user_id, "activity": activity.activity, "datetime": activity.datetime, }; let coll = conn.collection("activities"); coll.insert_one(doc, None).map(drop)}
This function only converts the Activity struct into a BSON document, and does this by extracting fields from a struct and construct BSON document with the same fields. We can derive the Serialize trait for the structure and use automatic serialization, but I used the doc! macro for demonstration ...
Read now
Unlock full access