@@ -206,7 +206,7 @@ def create_nested_pipeline(model: Type[BaseModel], prefix="", pipeline=None):
206
206
"timestamp" : "$timestamp" ,
207
207
}
208
208
209
- for field_name , _ in model .__fields__ .items ():
209
+ for field_name , field_type in model .__fields__ .items ():
210
210
if field_name == "timestamp" :
211
211
continue
212
212
lookup_field = (
@@ -221,11 +221,25 @@ def create_nested_pipeline(model: Type[BaseModel], prefix="", pipeline=None):
221
221
match_conditions [unit_field_name ] = {"$exists" : True }
222
222
elif field_name in nested_fields :
223
223
nested_model = nested_fields [field_name ]
224
- nested_prefix = f"{ full_mongo_field_name } ."
225
- nested_pipeline , nested_match = create_nested_pipeline (nested_model , nested_prefix )
226
- pipeline [field_name ] = nested_pipeline
227
- for k , v in nested_match .items ():
228
- match_conditions [f"{ nested_prefix } { k } " ] = v
224
+ if get_origin (field_type ) is List :
225
+ # Handle array of nested objects (like RelayStatus)
226
+ nested_pipeline , nested_match = create_nested_pipeline (nested_model , "" )
227
+ pipeline [field_name ] = {
228
+ "$map" : {
229
+ "input" : f"${ full_mongo_field_name } " ,
230
+ "as" : "item" ,
231
+ "in" : {
232
+ k : f"$$item.{ v .replace ('$' , '' )} " for k , v in nested_pipeline .items ()
233
+ },
234
+ }
235
+ }
236
+ match_conditions [full_mongo_field_name ] = {"$exists" : True }
237
+ else :
238
+ nested_prefix = f"{ full_mongo_field_name } ."
239
+ nested_pipeline , nested_match = create_nested_pipeline (nested_model , nested_prefix )
240
+ pipeline [field_name ] = nested_pipeline
241
+ for k , v in nested_match .items ():
242
+ match_conditions [f"{ nested_prefix } { k } " ] = v
229
243
else :
230
244
pipeline [field_name ] = f"${ full_mongo_field_name } "
231
245
match_conditions [full_mongo_field_name ] = {"$exists" : True }
@@ -257,10 +271,11 @@ def create_model_instance(model: Type[BaseModel], data: dict, target_unit: Optio
257
271
instance_data [field_name ] = data .get (unit_field )
258
272
elif field_name in nested_fields :
259
273
nested_model = nested_fields [field_name ]
260
- if isinstance (field .type_ , List ):
274
+ if get_origin (field .type_ ) is List :
275
+ # Handle array of nested objects (like RelayStatus)
276
+ nested_data = data .get (field_name , [])
261
277
instance_data [field_name ] = [
262
- create_model_instance (nested_model , item , target_unit )
263
- for item in data .get (field_name , [])
278
+ create_model_instance (nested_model , item , target_unit ) for item in nested_data
264
279
]
265
280
else :
266
281
nested_data = data .get (field_name , {})
0 commit comments