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

标签 mongodb rust gridfs

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/

相关文章:

asynchronous - 将请求正文转发到 Actix-Web 中的响应

javascript - 将二进制对象保存到服务器上的 GridFS

mongodb - 如何在 mongo shell 中运行本地脚本 - 解决方案 load()

spring - @Document(collection = "Test") 在 MongoRepository 中不起作用 - Spring 数据 - mongodb

mongodb - Mongoose 中的 updateMany() 和 bulkWrite() 有什么区别?

reference - 如何从 Rc<RefCell<A>> 获取 &A 引用?

php - Mongodb 聚合 $lookup 返回空数组

rust - 为什么排序需要这么长时间?

java - org.bson.codecs.configuration.CodecConfigurationException : Can't find a codec for class org. hibernate.ogm.datastore.mongodb.type.GridFS

mongodb - 使用 angular、express 和 mongodb 的 gridfs 上传文件