Firestore JS中存储字节的合适类型及序列化失败问题
Firestore存储二进制数据序列化失败解决方案
问题场景
尝试将Uint8Array二进制数据转换为JS Blob或Firestore Bytes存储到Firestore时,触发序列化失败,原代码如下:
import { Bytes } from "firebase/firestore"; const bin = new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F]); // 将二进制数据转换为JS Blob或FirestoreJS Bytes const jsBlob = new Blob([bin]); const fsBytes = Bytes.fromUint8Array(bin); db.collection('your_collection').doc('your_document').set({ binaryData: jsBlob // binaryData: fsBytes });
触发的错误
- 使用JS Blob时:
Error: Value for argument "data" is not a valid Firestore document. Input is not a plain JavaScript object (found in field "binaryData").
- 使用Firestore Bytes时:
Error: Value for argument "data" is not a valid Firestore document. Couldn't serialize object of type "Bytes" (found in field "binaryData"). Firestore doesn't support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).
解决方案
Firestore JS SDK中支持的二进制类型是Firestore专属的Blob类型,而非浏览器原生的JS Blob。需要从firebase/firestore导入Blob,并通过Blob.fromUint8Array方法转换二进制数据。
修正后的代码:
import { Blob } from "firebase/firestore"; const bin = new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F]); // 使用Firestore Blob转换二进制数据 const firestoreBlob = Blob.fromUint8Array(bin); db.collection('your_collection').doc('your_document').set({ binaryData: firestoreBlob });
说明
- 浏览器原生JS Blob属于非Plain Object,Firestore无法序列化该类型;
- 旧版SDK中的
Bytes已被替换为Blob,直接使用Bytes会触发原型校验失败。
内容的提问来源于stack exchange,提问作者Anthony Bobenrieth
相关产品推荐
相关产品推荐

