micronaut-data icon indicating copy to clipboard operation
micronaut-data copied to clipboard

MongoDB Relationship Expects Object

Open SenorPez opened this issue 1 year ago • 2 comments

Expected Behavior

Relationship defined in the parent POJO:

@MappedEntity("starSystems")

...

    @Relation(value = ONE_TO_MANY, mappedBy = "starSystem")
    @Join("stars")
    private final Set<Star> stars;

Inverse relationship defined in the child POJO:

@MappedEntity("stars")

...

    @NonNull
    @Relation(value = MANY_TO_ONE)
    @Join("starSystems")
    private StarSystem starSystem;

MongoDB document, as described in https://www.mongodb.com/docs/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/#std-label-data-modeling-publisher-and-books. (There's no unbounded array issue as stars in a star system maxes out at 3.) IDs are Int32s.

{
    "_id": 867158537,
    "name":" Home",
    "stars":[
        -1593524705"
    ]
}

It is expected that the Set<Star> field of the POJO will be properly constructed from the "stars" collection using a lookup of the IDs in the "stars" array in the "starSystem" document.

Actual Behaviour

Instead, there's an 500 error. StarSystem can not be deserialized:

Caused by: io.micronaut.serde.exceptions.SerdeException: Unexpected token NUMBER, expected START_OBJECT 
 at 
	at io.micronaut.serde.bson.BsonReaderDecoder.createDeserializationException(BsonReaderDecoder.java:312)

Steps To Reproduce

  1. Create Parent and Child POJOs.
  2. Create Mongo documents.
  3. Attempt to read POJOs.

Environment Information

-JDK 21; not using any experimental features.

Example Application

No response

Version

4.4.4

SenorPez avatar Dec 31 '24 17:12 SenorPez

Can be worked around by nesting IDs in an object; suggest an improvement to the parser to avoid this extraneous information:

{
  "_id": 867158537,
  "name": "Home",
  "stars": [
    {
      "_id": -1593524705
    }
  ]
}

SenorPez avatar Jan 01 '25 04:01 SenorPez

If you have multiple or composite IDs you would need an object

dstepanov avatar Jan 08 '25 08:01 dstepanov