小编Nir*_*man的帖子

使用 Rust Mongo 驱动程序原型时,如何将 chrono::DateTime 字段序列化为 ISODate?

使用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.

mongodb bson rust serde

5
推荐指数
1
解决办法
1021
查看次数

在迭代函数体上具有生命周期的泛型值时,借用值的活动时间不够长

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)

lifetime rust

3
推荐指数
1
解决办法
264
查看次数

标签 统计

rust ×2

bson ×1

lifetime ×1

mongodb ×1

serde ×1