You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot从MongoDB读取PDF时出现locale字段无效错误求助

问题解决思路

核心错误定位

报错Field 'locale' is invalid in: { locale: "pdfs" }说明你在执行MongoDB查询/命令时,错误地将locale作为字段传入,但MongoDB并不支持这个参数。大概率是你误把**集合名称(pdfs)**写成了locale参数,而非用正确方式指定集合。

分步修正

1. 检查并修正MongoDB操作代码

  • 若使用Spring Data MongoDB的MongoTemplate:
    正确指定集合的方式是调用getCollection("pdfs"),而非在查询条件中加入locale字段。示例:
    // 错误写法(含locale参数)
    // Query query = new Query(Criteria.where("locale").is("pdfs"));
    // 正确写法:直接指定集合
    MongoCollection<Document> collection = mongoTemplate.getCollection("pdfs");
    // 执行查询
    Document result = collection.find(new Document("your_query_field", "value")).first();
    
  • 若使用原生MongoDB驱动:
    需先获取目标集合再执行查询,而非将集合名塞进查询条件:
    MongoDatabase database = mongoClient.getDatabase("your_db_name");
    MongoCollection<Document> collection = database.getCollection("pdfs");
    // 执行查询逻辑
    

2. 修正实体类配置(若用Spring Data注解)

如果你的PDF实体类使用了@Document注解,确保通过collection属性指定集合名,而非错误添加locale字段:

// 正确写法
@Document(collection = "pdfs")
public class PdfDocument {
    // 你的字段:id、content(二进制)、文件名等
}

3. PDF内容提取与展示

成功取回MongoDB中存储的PDF二进制数据后,用Apache PDFBox解析内容并返回前端(支持中英文内容):

// 假设从MongoDB获取的二进制数据为byte[] pdfData
try (PDDocument document = PDDocument.load(pdfData)) {
    PDFTextStripper textStripper = new PDFTextStripper();
    // 提取所有文本
    String pdfContent = textStripper.getText(document);
    // 将pdfContent返回给前端渲染展示
} catch (IOException e) {
    e.printStackTrace();
}

内容的提问来源于stack exchange,提问作者Shivansh shukl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 13:01:03