使用Firebase Python SDK的ArrayUnion触发TypeError错误排查
问题分析与解决方案
问题场景
使用Python的firebase-admin对接Firestore,尝试通过ArrayUnion将User文档引用添加到Admin文档的users数组时触发TypeError,错误提示期望消息对象但得到字段路径。相关信息如下:
数据库连接代码
import firebase_admin from firebase_admin import credentials, db, firestore # Initialize connection to firebase cred = credentials.Certificate("serviceAccountKey.json") app_options = { 'databaseURL': '...'} firebase_admin.initialize_app(cred) db = firestore.client()
文档结构
Admin: {'users': [], 'email': '...', 'first_name': '...', 'last_name': '...'} User: {'email': '...', 'onboarding_form': {'first_name': '...', 'last_name': '...'}}
出错的更新代码
user_id = get_user_id(user_last_name, user_first_name) admin_id = get_admin_id(admin_last_name, admin_first_name) user_ref = db.collection(u'user').document(user_id) admin_ref = db.collection(u'admin').document(admin_id) admin_ref.update( {u'users': firestore.ArrayUnion([user_ref])})
错误堆栈信息
Traceback (most recent call last): File "/home/primrose/work/BE/db_api.py", line 109, in <module> test_run() File "/home/primrose/work/BE/db_api.py", line 106, in test_run add_user("...", "...", "...", "...") File "/home/primrose/work/BE/db_api.py", line 98, in add_user admin_ref.update( File "/home/primrose/.local/lib/python3.10/site-packages/google/cloud/firestore_v1/document.py", line 324, in update batch, kwargs = self._prep_update(field_updates, option, retry, timeout) File "/home/primrose/.local/lib/python3.10/site-packages/google/cloud/firestore_v1/base_document.py", line 239, in _prep_update batch.update(self, field_updates, option=option) File "/home/primrose/.local/lib/python3.10/site-packages/google/cloud/firestore_v1/base_batch.py", line 141, in update write_pbs = _helpers.pbs_for_update( File "/home/primrose/.local/lib/python3.10/site-packages/google/cloud/firestore_v1/_helpers.py", line 941, in pbs_for_update update_pb.update_transforms.extend(field_transform_pbs) TypeError: Expected a message object, but got field_path: "users" append_missing_elements { values { reference_value: ".../databases/(default)/documents/user/hlCcG1oFW4Z75JKqp1ZcfM8xWlh1" } } .
环境依赖版本
Name: firebase-admin Version: 5.2.0 Name: protobuf Version: 4.21.2
错误原因
firebase-admin 5.2.0属于旧版本,其内部依赖的protobuf版本为3.x系列,而你当前使用的protobuf 4.x版本在API层面存在不兼容变更,导致Firestore SDK处理ArrayUnion这类字段更新操作时,无法正确转换protobuf消息对象,进而触发类型错误。
解决方案
有两种可行的解决方式:
方式一:降级protobuf到兼容版本
执行命令将protobuf降级到firebase-admin 5.2.0官方兼容的3.x稳定版本:
pip install protobuf==3.20.3
方式二:升级firebase-admin到支持protobuf 4.x的版本
若需保留protobuf 4.x,可升级firebase-admin到v6.0.0及以上版本(该版本开始支持protobuf 4.x):
pip install --upgrade firebase-admin
升级后需确认基础操作代码适配新版本SDK(大部分核心API兼容,若有特殊逻辑可参考官方文档调整)。
内容的提问来源于stack exchange,提问作者Cherry Toska
相关产品推荐
相关产品推荐

