使用Rust Mongo 驱动程序原型时,结构中的日期时间字段被序列化为Strings 而不是ISODates 。如何获取要另存为的字段?ISODate
use chrono::{DateTime, Utc};
use mongodb::oid::ObjectId;
use mongodb::{
coll::Collection, db::Database, db::ThreadedDatabase, error::Error, Client, ThreadedClient,
};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug)]
struct Person {
pub _id: ObjectId,
pub date: DateTime<Utc>,
}
fn main() {
let client = Client.with_uri("mongodb://localhost:27017").unwrap();
let p = Person {
_id: ObjectId::new().unwrap(),
date: Utc::now(),
};
let document = mongodb::to_bson(p).unwrap().as_document();
if document.is_some() {
client
.db("my_db")
.collection("mycollection")
.insert_one(document, None)
.unwrap();
}
}
Run Code Online (Sandbox Code Playgroud)
在查询数据库时,记录包含一个日期字符串(ISO 格式);我希望它是一个ISODate.
fn func<'a, T>(arg: Vec<Box<T>>)
where
String: From<&'a T>,
T: 'a,
{
let s: Vec<String> = arg.iter().map(|s| String::from(s)).collect();
do_something_else(arg);
}
fn do_something_else<T>(arg: Vec<Box<T>>) {}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨说arg活不了多久.为什么呢?
error[E0597]: `arg` does not live long enough
--> src/lib.rs:6:26
|
6 | let s: Vec<String> = arg.iter().map(|s| String::from(s)).collect();
| ^^^ borrowed value does not live long enough
7 | do_something_else(arg);
8 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined …Run Code Online (Sandbox Code Playgroud)