首页 > 解决方案 > 无法使用 Functions:Shell 将新文档添加到 Firestore 中的集合

问题描述

我正在尝试使用 Firebase shell 将文档添加到 Firestore 中的子集合:

firebase functions:shell

运行它为我们提供了一个外壳,我们可以在其中运行查询和代码。似乎出于某种奇怪的原因,我无法将add文档记录到集合中。

这是我在 shell 中运行的脚本:

  await db.collection('balances')
    .doc(docId)
    .collection('history')
    .add({x: 'a'});

这很简单,但 Firebase 似乎不喜欢将该对象传递给 add 函数。

我能够到达谷歌的 Firestorevalidate.js文件中一切都失败的确切行。

function extractBaseClassName(value) {
    let constructorName = 'Object';
    while (Object.getPrototypeOf(value) !== Object.prototype) {
        value = Object.getPrototypeOf(value); // <===== This returns null instead of an Object for some reason
        constructorName = value.constructor.name;
    }
    return constructorName;
}

这是确切的错误消息堆栈:

(node:90760) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'constructor' of null
    at extractBaseClassName (/Users/Moose/Development/crypto-accumulator/functions/node_modules/@google-cloud/firestore/build/src/validate.js:35:33)
    at Object.customObjectMessage (/Users/Moose/Development/crypto-accumulator/functions/node_modules/@google-cloud/firestore/build/src/validate.js:55:26)
    at Object.validateDocumentData (/Users/Moose/Development/crypto-accumulator/functions/node_modules/@google-cloud/firestore/build/src/write-batch.js:608:36)
    at CollectionReference.add (/Users/Moose/Development/crypto-accumulator/functions/node_modules/@google-cloud/firestore/build/src/reference.js:1765:23)
    at runB (repl:43:6)
    at process._tickCallback (internal/process/next_tick.js:68:7)

更新:预感...

我相信问题可能在于Object.getPrototypeOf(value) !== Object.prototype评估true它应该是什么时候,false因为它{x: 'a'}是一个对象

标签: javascriptfirebasegoogle-cloud-platformgoogle-cloud-firestore

解决方案


看来对象不是问题。我试图在我的 Firestore 中重现它并使用以下命令:

let  docId = 'test_document3'
async function f1() { 
    await db.collection('test_collection').doc(docId).collection('inside-collection').add({ x: 'c'}) 
}
f1()

文档已添加,没有问题。你可以尝试同样的方法。


推荐阅读