fix: fix a mongodb _id issue

This commit is contained in:
haolou 2025-11-07 17:45:43 +08:00
parent 9f8892a8a9
commit 77a37da90f

View File

@ -284,11 +284,12 @@ class BaseDoc(BaseModel, metaclass=QueryModelMeta):
doc_dict = self._convert_decimals_to_float(doc_dict)
# Respect pre-populated id by mapping to MongoDB _id
if getattr(self, 'id', None):
id_value = getattr(self, 'id', None)
if id_value and not isinstance(id_value, QueryExpression):
try:
doc_dict['_id'] = ObjectId(self.id)
doc_dict['_id'] = ObjectId(id_value)
except Exception:
doc_dict['_id'] = self.id
doc_dict['_id'] = id_value
result = await collection.insert_one(doc_dict)
@ -322,12 +323,13 @@ class BaseDoc(BaseModel, metaclass=QueryModelMeta):
elif hasattr(self, 'auth_code'):
query['auth_code'] = self.auth_code
if getattr(self, 'id', None):
id_value = getattr(self, 'id', None)
if id_value and not isinstance(id_value, QueryExpression):
# Update by primary key when available
try:
object_id = ObjectId(self.id)
object_id = ObjectId(id_value)
except Exception:
object_id = self.id
object_id = id_value
result = await collection.update_one({"_id": object_id}, {"$set": doc_dict}, upsert=True)
if result.upserted_id: