【问题标题】:MongoDB throwing BsonInvalidOperationException when accessing GridFSMongoDB 在访问 GridFS 时抛出 BsonInvalidOperationException
【发布时间】:2017-08-06 11:42:37
【问题描述】:

这段代码:

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

【问题讨论】:

    标签: java mongodb gridfs


    【解决方案1】:

    当“元数据”字段为空时,我也看到了同样的问题。当文件的“元数据”字段为空时,mongo-java-driver 似乎会引发异常。但是它应该是可选的 (https://docs.mongodb.com/manual/core/gridfs/#files.metadata)。

    也检查其他字段。您可能会在文档中的某处有一个空值。

    “元数据”存在 Jira 问题 (https://jira.mongodb.org/browse/JAVA-2577)。

    更新

    https://jira.mongodb.org/browse/JAVA-2577 的回答:metadata 字段不应为空。

    更新 2

    我找到了一个使用 3.x 驱动程序中可用的旧 MongoDB API 的解决方案,但它将被弃用。

    GridFS gridFs = new GridFS(client.getDB("genisys"), "fs");
    gridFs.getFileList().forEach(f -> System.out.println(f.get("filename")));
    

    【讨论】:

    • 是的,fs.files 中有一些为空的元数据,但是我现在正在处理 137K 文件
    • 收到了Java驱动团队的答复。我已经更新了我的答案。
    • 我找到了方法,请查看UPDATE 2
    猜你喜欢
    • 2019-04-09
    • 2017-11-19
    • 2013-10-03
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多