Search code examples
javaspringspring-bootspring-dataspring-data-mongodb

Spring Boot Mongo Find Query Partial Results on Mapping Error


I'm trying to figure out how to still return partial results if there is a mapping error once the results are retrieved from mongo.

Mongo Query (MongoOperations mongoTemplate)

List<ProfileMongo> profileMongoList = mongoTemplate.find(query, ProfileMongo.class);

Exception:

org.springframework.data.mapping.MappingException: Cannot convert [Document{{id=90050, blablabla}}] of type class java.util.ArrayList into an instance of class com.models.mongodb.ProfileMongo$SegmentTargetingGroupIncludeExcludeMongo! Implement a custom Converter<class java.util.ArrayList, class com.models.mongodb.ProfileMongo$SegmentTargetingGroupIncludeExcludeMongo> and register it with the CustomConversions. Parent object was: [empty]",

The problem is there is a failure in the mapping process from a particular record and this causes an error to be thrown. I'm trying to figure out if there is anyway to just return the partial results that WERE able to map?


Solution

  • Had to get creative to make this work. I'm returning the BSON directly and then mapping it myself. see below

            List<ProfileMongo> profileMongoList = mongoTemplate.find(query, Bson.class, ProfileRepository.COLLECTION)
                    .stream().map(bson -> {
                        // Map BSON to ProfileMongo
                        ProfileMongo profileMongo = null;
                        try {
                            profileMongo = mongoTemplate.getConverter().read(ProfileMongo.class, bson);
                        } catch (Exception e) {
                            log.error("Failed to map profile");
                        }
                        return profileMongo;
                    }).toList();