Retrieve MongoDB Document as POJO

Viewed 12

I'm trying to figure out how to retrieve documents from my MongoDB Atlas database as POJOs. I'm having a very hard time with this, despite having spent a couple hours reading other questions on here and github. Here is my code:

public static void main(String[] args) {
    String uri = URIHandler.URI;
    CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
    CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
    MongoDatabase database;

    Dog dog = new Dog("d84jmv94", "Husky", 120, "Frost", 3);

    try (MongoClient mongoClient = MongoClients.create(uri)) {
        database = mongoClient.getDatabase("Jars").withCodecRegistry(pojoCodecRegistry);
        MongoCollection<Dog> collection = database.getCollection("Jars", Dog.class);

        collection.insertOne(dog);

        Document query = new Document().append("id", "d84jmv94");

        Dog myDog = collection.find(query).first();

        System.out.println(myDog.getName());
    }
}

I have checked my collection, and the Dog object posted just fine. However, when it tries to retrieve it and call getName(), I get the following output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.codenamebear.Dog.getName()" because "myDog" is null
0 Answers
Related