【问题标题】:Cannot save “custom blob” to Firestore - ADMIN SDK无法将“自定义 blob”保存到 Firestore - ADMIN SDK
【发布时间】:2019-05-22 23:34:17
【问题描述】:

跟进我已经完成的一个较早的问题here 现在我在管理 SDK 上遇到了同样的问题,但无法解决这个问题。

我正在尝试将 blob 保存到 Firestore,但我得到:

 Error: Value for argument "data" is not a valid Firestore document. Couldn't serialize object of type "Blob" (found in field data). Firestore doesn't support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).

以下是我将自定义 Blob 转换为 Firestore Blob 的方法:

// The import
import {firestore} from "firebase";

// The function 
export const parseQueue = functions.region('europe-west2').pubsub.schedule('every 1 minutes').onRun(async (context) => {

....code...

// The problem
writePromises.push(
          admin.firestore()
            .collection('users')
            .doc(userID)
            .collection('events')
            .doc(<string>event.getID())
            .collection('activities')
            .doc(<string>activity.getID())
            .collection('streams')
            .doc(stream.type)
            .set({
              type: stream.type,
              data: firestore.Blob.fromBase64String(new Buffer((Pako.gzip(JSON.stringify(stream.data), {to: 'string'})), 'binary').toString('base64')),
            }))

当我使用前面提到的错误调用 set 时,上述崩溃。

firestore.Blob.fromBase64String 函数运行良好,我确实得到了一个很好的 blob。

我做错了什么?

【问题讨论】:

    标签: javascript node.js firebase google-cloud-firestore blob


    【解决方案1】:

    “firebase”模块不是 Admin SDK 的一部分,它是客户端 SDK。您不能将其与 firebase-admin 混合使用。如果您要将它们作为参数传递给 firebase-admin SDK 方法,请仅使用 firebase-admin 提供的符号和 API。您可能应该从您的项目中完全删除模块“firebase”。

    您没有显示它,但我假设您已经像以下之一那样导入了 firebase-admin:

    import * as admin from 'firebase-admin'
    const admin = require('firebase-admin')
    

    现在,任何时候您想使用 Firestore API,您通常都会通过其提供的 firestore 对象:

    const firestore = admin.firestore
    

    您已经通过致电admin.firestore().collection()... 执行此操作一次。它基本上是从Cloud Firestore SDK for nodejs 重新导出所有内容。

    您在客户端 SDK 中使用的 Blob 对象不是由服务器 SDK 提供的。如果你想写一个字节数组,你必须直接使用节点的Buffer对象。

    doc.set({
        type: stream.type,
        data: new Buffer((Pako.gzip(JSON.stringify(stream.data), {to: 'string'})), 'binary')
    })
    

    或者您需要做的任何事情来制作正确的缓冲区。

    【讨论】:

    • 我认为 blob 是/曾经是问题。现在看看,谢谢
    • 鼓声!谢谢!
    • 我注意到的一件事:客户端不接受缓冲区,需要 firestore.blob 此外,firestore.blob 与缓冲区方法会产生不同大小的二进制文件
    • 是的,客户端和服务器端代码会有所不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2023-02-22
    • 2011-08-30
    • 2017-01-12
    相关资源
    最近更新 更多