Home > Mobile >  Spring Boot Mongo Find Query Partial Results on Mapping Error
Spring Boot Mongo Find Query Partial Results on Mapping Error

Time:10-13

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?

CodePudding user response:

You can surround it with a try-catch block where the error is getting thrown.

Or you can also try the Builder pattern.

Builder delegates the object construction process to the user of the method, who if deems it un-necessary, won't construct the object and won't use the resources.

Or you can have default values (like null) where the parent object is empty.

CodePudding user response:

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();
  • Related