【问题标题】:Springboot With Mongodb Error while using find*() querySpringboot 使用 find*() 查询时出现 Mongodb 错误
【发布时间】:2020-04-19 07:36:35
【问题描述】:

我收到以下错误:

在 com.aks.springStorage.SpringStorageApplication.main(SpringStorageApplication.java:22) [classes/:na]
原因:org.springframework.data.mongodb.UncategorizedMongoDbException:查询失败,错误代码为 2,错误消息“字段 'locale' is invalid in: { locale: "company" }' on server localhost:27017;嵌套异常是 com.mongodb.MongoQueryException:查询失败,错误代码 2 和错误消息“字段 'locale' 在服务器 localhost:27017 上的 { locale: "company" }' 无效

奇怪的是我没有在公司集合中使用任何变量,如“语言环境”。我能够插入并获得计数,但没有一个 findAll* 是 工作,得到同样的错误。

public interface CompanyRepository extends MongoRepository<Company, String> {
    List<Company> findByName(String name);

    @Query("{'contact.address': ?0}")
    List<Company> findByAddress(String address);
}

@Document(collation = "company")
public class Company {
    private int id;
    private String name;
    private List<Product> products;
    private Contact contact;

    public Company(int id, String name, List<Product> products, Contact contact) {
        this.id = id;
        this.name = name;
        this.products = products;
        this.contact = contact;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }

    public Contact getContact() {
        return contact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }
}

// Client code:      
//this is working fine
int count = (int) companyRepo.count();

// Failing Here
companies = companyRepo.findByName("yy");

【问题讨论】:

  • collat​​ion="company" 好像是错字
  • @MadhavKumarJha 谢谢!这是一个拼写错误,我改为收藏。它奏效了。
  • 难以捉摸的“这个问题是一个错字,但应该留下,因为它是一个非常容易自动完成的错字”问题!

标签: mongodb spring-boot


【解决方案1】:
@Document(collation="company")

这看起来像是一个错字,也是您的问题的原因。您尝试设置集合名称,但您使用 collation 属性而不是 collection 属性:https://docs.mongodb.com/manual/reference/collation/

注释的正确形式是:

@Document(collection = "company")
public class Company {
    // ...
}

或者更简单——因为valuecollection 的别名:

@Document("company")
public class Company {
    // ...
}

您甚至可以完全省略集合名称。在这种情况下,Spring 将使用类名作为集合名:

@Document // name of collection wil be "company", as per class name
public class Company {
    // ...
}

最后一个例子是为什么这对你有用,例如计数查询,即使您没有明确提供集合名称。

【讨论】:

  • 这是 intellij AutoSuggest 的问题 :)
【解决方案2】:

这有时会发生在您错过带有注释 @Document 的注释实体类时

  • 错了 @Document(collat​​ion = "部门")

  • 对 @Document(collection = "部门")

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2020-04-07
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    相关资源
    最近更新 更多