您的位置:首页 > 数据库 > Mongodb

【原】MongoDB Java版驱动调用GridFS.getFileList()报错:no gridfs!解决方法

2014-01-12 22:25 441 查看
使用驱动版本:mongo-java-driver-2.9.3.jar

问题原因:GridFS.getFileList()方法返回的GridFSDBFile对象的_fs字段未初始化

解决方法:利用Java的反射机制手工赋值

代码示例:

Mongo mongo = new Mongo("localhost", 27017);

DB db = mongo.getDB("demo");

GridFS fs = new GridFS(db, theme);

DBCursor fileList = fs.getFileList();

Field _fs = GridFSFile.class.getDeclaredField("_fs"); // _fs字段所在的类为GridFSFile
_fs.setAccessible(true);
while (fileList.hasNext()) {
GridFSDBFile next = (GridFSDBFile) fileList.next();

// XXX bug 修复_fs字段为空的问题
_fs.set(next, fs);

// 保存文件操作
next.writeTo(next.getId().toString());

// 其他操作
...

}

fileList.close();
mongo.close();


另:

GridFS的findOne(...),find(...)方法内都调用了GridFS._fix( Object o )方法对此问题进行了修正,所以一般这个问题也不容易被发现。没想到刚刚开始学习MongoDB就中枪。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: