kuttifunk
kuttifunk

Reputation: 141

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

The mongodb 0.1.4 bindings for Rust provide a GridFS implementation. As from the code and the examples there is a put, but it doesn't return an object ID.

My workaround is to put the file into GridFS and then open it again to retrieve the 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
}

Is there a better way?

Upvotes: 0

Views: 407

Answers (1)

Shepmaster
Shepmaster

Reputation: 431529

I don't have MongoDB running and I don't really know anything about it, but this at least has the right signature and compiles.

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())
}

Recall that most Rust libraries are open-source and you can even browse the source directly from the documentation. This function is basically just a hacked version of the existing put.

Upvotes: 1

Related Questions