Skip to content

Commit 98dea19

Browse files
committed
Attempt to fix nested model retrival
1 parent b24ca81 commit 98dea19

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
lines changed

opensensor/collection_apis.py

+24-9
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ def create_nested_pipeline(model: Type[BaseModel], prefix="", pipeline=None):
206206
"timestamp": "$timestamp",
207207
}
208208

209-
for field_name, _ in model.__fields__.items():
209+
for field_name, field_type in model.__fields__.items():
210210
if field_name == "timestamp":
211211
continue
212212
lookup_field = (
@@ -221,11 +221,25 @@ def create_nested_pipeline(model: Type[BaseModel], prefix="", pipeline=None):
221221
match_conditions[unit_field_name] = {"$exists": True}
222222
elif field_name in nested_fields:
223223
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
229243
else:
230244
pipeline[field_name] = f"${full_mongo_field_name}"
231245
match_conditions[full_mongo_field_name] = {"$exists": True}
@@ -257,10 +271,11 @@ def create_model_instance(model: Type[BaseModel], data: dict, target_unit: Optio
257271
instance_data[field_name] = data.get(unit_field)
258272
elif field_name in nested_fields:
259273
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, [])
261277
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
264279
]
265280
else:
266281
nested_data = data.get(field_name, {})

0 commit comments

Comments
 (0)