首页 > 解决方案 > 如何使用函数写入我的 Firestore 数据库?

问题描述

我是firebase firestore的新手。我正在尝试将以下数据写入我的 Firestore 数据库:

    export const testingOnly = functions.database.ref('users/{userID}/')
.onCreate((snapshot, context) => {
    let addDoc = {
        c_username: 'Amanda',
        c_password: 'adamma21',
        isEmailConfirmed: true,
        isTelephoneNumberConfirmed: false
    }
    return snapshot.ref.set(addDoc);
});

紧接着,我在终端上运行了以下命令:

npm run-script build

firebase functions: shell

It showed me this:

 C:\brighterbrains\functions> npm run-script build

> functions@ build C:\brighterbrains\functions
> tsc

PS C:\brighterbrains\functions> firebase functions:shell
!  Your requested "node" version "8" doesn't match your global version "12"       
+  functions: Emulator started at http://localhost:5000
i  functions: Loaded functions: testingOnly
firebase > testingOnly
[Function: bound ]
firebase >

我检查了我的 Firestore 数据库,它仍然是空的。

我这样做对吗?我的代码有什么遗漏吗?

我需要帮助。

标签: node.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


请注意,尚不清楚您的 Cloud Function 是否应由实时数据库(如您的代码所示)或Cloud Firestore(如您的问题文本所示)中的事件触发。


Firebase CLI 包含一个 Cloud Functions 模拟器,允许在本地运行 Cloud Functions。但是,在撰写本文时,此模拟器只能模拟以下函数类型,请参阅文档

  • HTTPS 功能
  • 可调用函数
  • Cloud Firestore 功能

因此,由于您的 Cloud Function 似乎是由实时数据库中的事件触发的,因此您需要部署它才能运行它。有关如何继续的更多详细信息,请参阅此“入门”文档或观看“使用 TypeScript 开始使用 Cloud Functions for Firebase”视频,该视频使用 TypeScript,但也适用于 JavaScript 的 CLI 部分。


另一方面,如果您真的想通过 Cloud Firestore 中的事件触发它,您应该首先更改函数的代码(参见上面提到的文档),然后按照文档中的说明使用模拟器(或部署它) .


推荐阅读