如何从云火商店数据库中获取特定字段数据?

Dev*_*er 6 javascript node.js firebase google-cloud-functions google-cloud-firestore

我能够访问数据文档数据,但无法访问卡的其他字段数据,如电子邮件。在 .get() 函数上出错。

在此处输入图片说明

功能

exports.StripeSource =functions.firestore.document('data/{card}/tokens/{tokenid}').onCreate(async (tokenSnap,context) => {
  const user_id = context.params.card;
  console.log('Document data:', user_id);
  var customerdata;
  const snapshot =  firestore.collection('test').doc('card');
  return snapshot
      .get()
      .then(doc => {
        if (!doc.exists) {
          console.log('No such User document!');
          console.log('Document data:', doc.data().email);

        } else {
          console.log('Document data:', doc.data());
          console.log('Document data:', doc.data().email);
          return true;
        }
      })
      .catch(err => {

        console.log('Error getting document', err);
        return false;
      });
  });
Run Code Online (Sandbox Code Playgroud)

我运行代码并在控制台中收到此错误

[![TypeError: snapshot.get is not a function
    at exports.StripeSource.functions.firestore.document.onCreate (/srv/index.js:13:8)
        at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
        at /worker/worker.js:825:24
        at <anonymous>
        at process._tickDomainCallback (internal/process/next_tick.js:229:7)][2]][2]
Run Code Online (Sandbox Code Playgroud)

Ren*_*nec 5

如果您想在 Cloud Function 中读取/写入 Firestore,您需要使用 Admin SDK,并且您必须执行以下操作:

const snapshot =  admin.firestore.collection('test').doc('card');
Run Code Online (Sandbox Code Playgroud)

代替

const snapshot =  firestore.collection('test').doc('card');
Run Code Online (Sandbox Code Playgroud)

请注意,您需要使用 Node require 语句导入 Admin SDK 模块。将这些行添加到您的 index.js 文件中:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
Run Code Online (Sandbox Code Playgroud)

另请注意,调用变量snapshot可能会导致一些错误(即由于错误命名而混淆变量类型)。

通过这样做,admin.firestore.collection('test').doc('card');您定义了一个DocumentReference. 通过调用异步get()方法,您将获得DocumentSnapshot.


最后,不要忘记在您的 Cloud 函数中返回一个 Promise 或一个值(如果不返回任何内容!doc.exists)。值得观看 Firebase 视频系列中关于“JavaScript Promises”的 3 个视频:https ://firebase.google.com/docs/functions/video-series/