Skip to content

Commit

Permalink
Improve handling of MongoDB ObjectIDs
Browse files Browse the repository at this point in the history
  • Loading branch information
ml-evs committed May 6, 2022
1 parent b38dab7 commit df277b8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
3 changes: 0 additions & 3 deletions optimade/server/entry_collections/entry_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,6 @@ def handle_query_params(
for f in self.all_fields
}

if "_id" not in cursor_kwargs["projection"]:
cursor_kwargs["projection"]["_id"] = False

if getattr(params, "response_fields", False):
response_fields = set(params.response_fields.split(","))
response_fields |= self.resource_mapper.get_required_fields()
Expand Down
15 changes: 10 additions & 5 deletions optimade/server/entry_collections/mongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,16 @@ def _run_db_query(
"""

results = []
for doc in self.collection.find(**criteria):
if criteria.get("projection", {}).get("_id"):
doc["_id"] = str(doc["_id"])
results.append(doc)
# Handle MongoDB ObjectIDs:
# - If they were not requested, then explicitly remove them
# - If they were requested, then cast them to strings in the response
if "_id" not in criteria["projection"]:
criteria["projection"]["_id"] = False

if criteria.get("projection", {}).get("_id"):
criteria["projection"]["_id"] = {"$toString": "$_id"}

results = list(self.collection.find(**criteria))

nresults_now = len(results)
if not single_entry:
Expand Down

0 comments on commit df277b8

Please sign in to comment.