2016-07-27 84 views
0

mongodb 0.1.4 bindings for Rust提供了一個GridFS實現。 從代碼和示例中,有一個put,但它不返回對象ID。如何使用Rust MongoDB驅動程序從添加到GridFS的文件中獲取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 
} 

有沒有更好的辦法?

回答

1

我沒有運行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的黑客版本。

+0

非常感謝您的幫助。 – kuttifunk

+0

中斷...非常感謝您花時間幫助我完成所有事情。喜歡:編輯堆棧溢出問題:我是一個完全noob在這裏,相當monadic錯誤處理與嘗試!:我仍然在學習,最重要的是我問的問題:我想當我使用file.close()然後後綴我不是允許訪問不正確的file.doc.id。一遍又一遍地閱讀源代碼。再次感謝,好工作!我真的很感激! – kuttifunk

相關問題