-1

I have a POJO

public class Model {
 String name;
}


    public class MyClass {
      @id
      String _id;
      ArrayList<Model> models;
    }

I am trying to add another entry in the models array with this json -

{

  "models": [
    {
        "name" : "string"
    },
    {
        "name" : "string244"
    }
  ]
}

And this is the java code for same -

  @PutMapping("/myClass/{id}")
  public ResponseEntity<MyClass> addModel(@PathVariable("id") String recId,
      @Valid @RequestBody MyClass myClass)  {

    Query query = new Query(Criteria.where("_id").is(recId));
    Update update = new Update().push("models", myClass.models);
    MyClass myNewClass = mongoOperations.findAndModify(query, update, MyClass.class);
    return new ResponseEntity<>(myNewClass, HttpStatus.OK);
  }

But spring is unable to convert my json into the MyClass POJO. Getting this exception -

org.springframework.data.mapping.MappingException: Cannot convert [Document{{name=string}}, Document{{name=string244}}] of type class java.util.ArrayList into an instance of class com.trustin.model.Model! Implement a custom Converter<class java.util.ArrayList, class com.trustin.model.Model> and register it with the CustomConversions. Parent object was: com.trustin.model.MyClass@335afcef -> null
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readCollectionOrArray(MappingMongoConverter.java:1099) ~[spring-data-mongodb-2.2.0.RELEASE.jar:2.2.0.RELEASE]

How do I add another element to the model array in my collection ?

1 Answers1

0

Solved it.

Use set instead of push in query.