Completely stuck here. I have a struct representing a course, where I use a NaiveDatetime field to show when the course will take place. I am having no luck figuring out how to store this as a DateTime object in mongodb though.
I won't try to put all the code variations I tried here, it could fill a book, I will instead ask bluntly if anyone has a working example where you receive JSON data and it can store it properly. The JSON sent looks like
{"course_name":"Tryout", "course_datetime":"2020-03-28T16:29:04.644008111Z" }
Here is the small struct(I removed the optional fields for clarity)
This is the last iteration, which uses the serde_helper, but I tried a bazilion variation while trying to decipher the mongodb and bson crate doc(I am not the best at reading/understanding API doc..)
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use mongodb::bson::{oid::ObjectId, DateTime};
use mongodb::bson::serde_helpers::bson_datetime_as_rfc3339_string;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CreateCourse {
pub course_name: String,
#[serde(with = "bson_datetime_as_rfc3339_string")]
pub course_datetime: DateTime,
}
and the database write function just in case.
pub async fn post_new_course_db(
pool: &Database,
new_course: CreateCourse,
) -> Result<Course, ZataError> {
let collection = pool.collection::<CreateCourse>("zata_course");
let resp = collection.insert_one(new_course, None).await?;
//Retrieve result
let collection = pool.collection::<Course>("zata_course");
let course_doc = collection.find_one(doc! {
"_id": resp.inserted_id
},
None,
).await?
.unwrap();
Ok(course_doc)
}
The best I managed to achieve was to have the JSON data accepted, but it was stored as a String in mongoDB
Any tips, help, clues?