mongodb 0.1.4 bindings for Rust提供 GridFS 实现。
从代码和示例中可以看出,有一个 put
,但它不返回对象 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
的黑客版本。
关于mongodb - 如何使用 Rust MongoDB 驱动程序从添加到 GridFS 的文件中获取 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38616053/