Search code examples
mongodbserializationpojocodecbson

Mongodb PojoCodec Found property not present in the ClassModel: id


Be me, perform aggregate query on MongoDb:

db.Rubrica.aggregate([
{$match: {"fiscalCode": "asfjhsdfhgsdfugsdf"}},
{$project: {
    "_id":0,
    "contactsHeaders":"$contacts.header",
}}
]);

Get the result:

{
    "contactsHeaders" : [
        {
            "id" : "7b47c1637cde49d182b96bcc33d21d0d",
            "alias" : "VOL LISTA",
            "type" : "L"
        },
        {
            "id" : "ab31c06ecce244bea4ab5b45b89f4fdc",
            "alias" : "VOL FEDRO",
            "type" : "S"
        }
    ]
}

Now in Java i try to deserialize the Document in:

public class ListOfHeadersWrapper implements Serializable  {
     List<Header> contactsHeaders;
....
....

public class Header implements Serializable {
    private String id;
    private String alias;
    private TypeEnum type;

    public String getId() {
        return id;
    }

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

What I get is:

{
    "contacts": [
    {
      "id": null,
      "alias": "VOL LISTA",
      "type": "L"
    },
    {
      "id": null,
      "alias": "VOL FEDRO",
      "type": "S"
    }
  ]
}

id is always null. Logs says Found property not present in the ClassModel: id.

If I deserialize the thing manually with Jackson:

(new ObjectMapper()).readValue(res.toJson(), ListOfHeadersWrapper.class).toString()

I get the correct result:

ListOfHeadersWrapper{contactsHeaders=[Header{id='7b47c1637cde49d182b96bcc33d21d0d', alias='VOL

WHY????


Solution

  • Adding @BsonProperty("id") does the trick:

    public class Header implements Serializable {
        @BsonProperty("id")
        private String id;
        ...
        ...
    

    This I think only happens for CosmosDb when used with MongoApi.