【原】MongoDB Java版ドライバ呼び出しGridFS.getFileList()エラー:no gridfs!解決策


ドライババージョンの使用:mongo-java-driver-2.9..3.jar
質問理由:GridFS.getFileList()メソッドが返すGridFSDBFileオブジェクトの_fsフィールドは初期化されていません
 
解決方法:Javaの反射メカニズムを利用して手動で値を割り当てる
コードの例:
 1 Mongo mongo = new Mongo("localhost", 27017);
 2  
 3 DB db = mongo.getDB("demo");
 4  
 5 GridFS fs = new GridFS(db, theme);
 6  
 7 DBCursor fileList = fs.getFileList();
 8  
 9  
10 Field _fs = GridFSFile.class.getDeclaredField("_fs"); // _fs       GridFSFile
11 _fs.setAccessible(true);
12 while (fileList.hasNext()) {
13     GridFSDBFile next = (GridFSDBFile) fileList.next();
14  
15     // XXX bug   _fs       
16     _fs.set(next, fs);
17  
18     //       
19     next.writeTo(next.getId().toString());
20  
21     //     
22     ...
23  
24 }
25  
26 fileList.close();
27 mongo.close();

 
追加:
GridFSのfindOne(…)、find(…)メソッド内でGridFSが呼び出されます.fix( Object o )方法はこの問題を修正したので、一般的にこの問題も発見されにくい.意外にもモンゴDBの勉強を始めたばかりで銃に当たった.
 
転載先:https://www.cnblogs.com/longhua828/p/mongdb_java_no_gridfs_error_fix.html