sanjana2505006 commented on code in PR #15583:
URL: https://github.com/apache/grails-core/pull/15583#discussion_r3105522382


##########
grails-data-mongodb/bson/src/main/groovy/org/grails/datastore/bson/codecs/encoders/IdentityEncoder.groovy:
##########
@@ -41,6 +41,25 @@ class IdentityEncoder implements PropertyEncoder<Identity> {
     void encode(BsonWriter writer, Identity property, Object id, EntityAccess 
parentAccess, EncoderContext encoderContext, CodecRegistry codecRegistry) {
         writer.writeName(getIdentifierName(property))
 
+        Class<?> storedAs = resolveStoredAs(property)
+        if (storedAs != null && id != null) {
+            if (ObjectId.isAssignableFrom(storedAs) && !(id instanceof 
ObjectId)) {
+                String hex = id.toString()
+                // Guard against natural-key strings accidentally paired with 
storedAs: ObjectId.
+                // new ObjectId(<non-hex>) throws IllegalArgumentException, 
which would surface
+                // deep inside the BSON write pipeline. Fall through to 
writeString for consistency
+                // with the converter-based paths (MongoCodecSession, 
MongoCodecEntityPersister).
+                if (ObjectId.isValid(hex)) {
+                    writer.writeObjectId(new ObjectId(hex))
+                    return
+                }
+            }

Review Comment:
   I noticed that if `ObjectId.isValid(hex)` is false, it falls through to 
write a BSON String. While this prevents a crash during save, the `Converter` 
added in `MongoMappingContext` returns `null` for invalid hex strings. This 
creates an asymmetry where a document can be saved with a non-hex ID (like a 
slug) but then becomes unreachable via `Domain.get(id)` because the query will 
target `{_id: null}`.
   
   Should we ensure the query path also falls back to the original String if 
it's not a valid hex, to maintain consistency?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to