MongoDB 访问 GridFS 时抛出 BsonInvalidOperationException
MongoDB throwing BsonInvalidOperationException when accessing GridFS
此代码:
ServerAddress serverAddress = new ServerAddress(url, Integer.valueOf(port));
MongoCredential credential = MongoCredential.createScramSha1Credential(username,"admin",
password.toCharArray());
MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
MongoDatabase mongoDatabase = mongoClient.getDatabase("admin");
GridFSBucket gridFSBucket = GridFSBuckets.create(mongoDatabase);
gridFSBucket.find().forEach(
new Block < GridFSFile > () {
@Override
public void apply(final GridFSFile gridFSFile) {
System.out.println(gridFSFile.getFilename());
}
});
引发此错误:
org.bson.BsonInvalidOperationException: Value expected to be of type DOCUMENT is of unexpected type NULL
at org.bson.BsonValue.throwIfInvalidType(BsonValue.java:419)
at org.bson.BsonValue.asDocument(BsonValue.java:47)
at org.bson.BsonDocument.getDocument(BsonDocument.java:506)
我对此感到困惑,因为使用 MongoDB 客户端(如 Robomongo)我可以看到 fs.files
当 "metadata" 字段为空时,我遇到了同样的问题。当文件的 "metadata" 字段为空时,mongo-java-driver
似乎会抛出异常。但是它应该是可选的 (https://docs.mongodb.com/manual/core/gridfs/#files.metadata).
也检查其他字段。文档中某处可能有空值。
"metadata" 有一个 Jira 问题
(https://jira.mongodb.org/browse/JAVA-2577).
更新
来自 https://jira.mongodb.org/browse/JAVA-2577 的回答:metadata
字段不应为空。
更新 2
我找到了旧的 MongoDB API 的解决方案,它在 3.x 驱动程序中可用,但将被弃用。
GridFS gridFs = new GridFS(client.getDB("genisys"), "fs");
gridFs.getFileList().forEach(f -> System.out.println(f.get("filename")));
此代码:
ServerAddress serverAddress = new ServerAddress(url, Integer.valueOf(port));
MongoCredential credential = MongoCredential.createScramSha1Credential(username,"admin",
password.toCharArray());
MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
MongoDatabase mongoDatabase = mongoClient.getDatabase("admin");
GridFSBucket gridFSBucket = GridFSBuckets.create(mongoDatabase);
gridFSBucket.find().forEach(
new Block < GridFSFile > () {
@Override
public void apply(final GridFSFile gridFSFile) {
System.out.println(gridFSFile.getFilename());
}
});
引发此错误:
org.bson.BsonInvalidOperationException: Value expected to be of type DOCUMENT is of unexpected type NULL
at org.bson.BsonValue.throwIfInvalidType(BsonValue.java:419)
at org.bson.BsonValue.asDocument(BsonValue.java:47)
at org.bson.BsonDocument.getDocument(BsonDocument.java:506)
我对此感到困惑,因为使用 MongoDB 客户端(如 Robomongo)我可以看到 fs.files
当 "metadata" 字段为空时,我遇到了同样的问题。当文件的 "metadata" 字段为空时,mongo-java-driver
似乎会抛出异常。但是它应该是可选的 (https://docs.mongodb.com/manual/core/gridfs/#files.metadata).
也检查其他字段。文档中某处可能有空值。
"metadata" 有一个 Jira 问题 (https://jira.mongodb.org/browse/JAVA-2577).
更新
来自 https://jira.mongodb.org/browse/JAVA-2577 的回答:metadata
字段不应为空。
更新 2
我找到了旧的 MongoDB API 的解决方案,它在 3.x 驱动程序中可用,但将被弃用。
GridFS gridFs = new GridFS(client.getDB("genisys"), "fs");
gridFs.getFileList().forEach(f -> System.out.println(f.get("filename")));