如何使用 Rust MongoDB 驱动程序从添加到 GridFS 的文件中获取 ID?

How to get ID from file added to GridFS with the Rust MongoDB driver?

mongodb 0.1.4 bindings for Rust 提供了 GridFS 实现。 从代码和示例来看,有一个 put,但它没有 return 一个对象 ID。

我的解决方法是将文件放入 GridFS,然后再次打开它以检索 ID:

fn file_to_mongo(gridfs: &Store, fpath: &PathBuf) -> bson::oid::ObjectId {
    gridfs.put(fpath.to_str().unwrap().to_owned());
    let mut file = gridfs.open(fpath.to_str().unwrap().to_owned()).unwrap();
    let id = file.doc.id.clone();
    file.close().unwrap();
    id
}

有没有更好的方法?

我没有 MongoDB 运行 并且我对此一无所知,但这至少具有正确的签名和编译。

extern crate bson;
extern crate mongodb;

use mongodb::gridfs::{Store,ThreadedStore};
use mongodb::error::Result as MongoResult;
use std::{fs, io};

fn my_put(store: &Store, name: String) -> MongoResult<bson::oid::ObjectId> {
    let mut f = try!(fs::File::open(&name));
    let mut file = try!(store.create(name));
    try!(io::copy(&mut f, &mut file));
    try!(file.close());
    Ok(file.doc.id.clone())
}

回想一下,大多数 Rust 库都是开源的,您甚至可以直接从文档中浏览源代码。这个功能基本上只是现有put.

的破解版