简体   繁体   English

从 firestore 文档中获取数据并在云端使用 function

[英]Get data from firestore document and use in cloud function

In the user's collection, each user has a document with a customer_id.在用户集合中,每个用户都有一个带有 customer_id 的文档。 I would like to retrieve this customer_id and use it to create a setup intent.我想检索此 customer_id 并使用它来创建设置意图。

The following code has worked for me in the past.以下代码过去对我有用。 However, all of a sudden it throws the error:然而,突然间它抛出错误:

Object is possibly 'undefined' Object 可能是“未定义的”

The error is on the following line under snapshot.data() in this line:该行中的snapshot.data()下的错误位于以下行:

const customerId = snapshot.data().customer_id;

Here is the entire code snippet:这是整个代码片段:

exports.createSetupIntent = functions.https.onCall(async (data, context) => {
  const userId = data.userId;
  const snapshot = await db
      .collection("development")
      .doc("development")
      .collection("users")
      .doc(userId).get();
  const customerId = snapshot.data().customer_id;
  const setupIntent = await stripe.setupIntents.create({
    customer: customerId,
  });
  const clientSecret = setupIntent.client_secret;
  const intentId = setupIntent.id;
  return {
    clientsecret: clientSecret,
    intentId: intentId,
  };
});

Any help is appreciated:)任何帮助表示赞赏:)

this is because snapshot.data() may return undefined这是因为 snapshot.data() 可能返回 undefined

there are 2 ways to solve this有两种方法可以解决这个问题

first is assert as non-null, if you have high confident that the data exist首先是断言为非空,如果您对数据存在高度确信

const customerId = snapshot.data()!.customer_id;

second if check for undefined第二个如果检查未定义

const customerId = snapshot.data()?.customer_id;

if(customerId){
  //  ....
}

I recommend the 2nd method, it is safer我推荐第二种方法,它更安全

I can see you are using a sub collection order,You need to loop through the snapshot data using the forEach loop.我可以看到您正在使用子集合顺序,您需要使用 forEach 循环遍历快照数据。


  const customerId = snapshot.data()
    customerId.forEach((id)=> {
       console.log(id.customer_id)
    });

Try this out but.试试这个但是。

The document you're trying to load may not exist, in which case calling data() on the snapshot will return null , and thus this line would give an error:您尝试加载的文档可能不存在,在这种情况下,在快照上调用data()将返回null ,因此这一行会给出错误:

const customerId = snapshot.data().customer_id;

The solution is to check whether the document you loaded exists, and only then force to get the data from it:解决方案是检查您加载的文档是否存在,然后才强制从中获取数据:

if (snapshot.exists()) {
  const customerId = snapshot.data()!.customer_id;
  ...
}

if you want to fetch user data from docId then you can use something like this:如果你想从 docId 获取用户数据,那么你可以使用这样的东西:

 const functions = require("firebase-functions");
 var admin = require('firebase-admin');     

 admin.initializeApp(functions.config().firebase);
 var db = admin.firestore();
 db.settings({ timestampsInSnapshots: true });     


 exports.demoFunction = functions.https.onRequest((request, response) => {
      var userId = request.body.userId;
      db.collection("user").doc(userId).get().then(snapshot => {
           if (snapshot) {
                var data = snapshot.data();
                // use data to get firestore data
                var yourWantedData = data.name;
                // use it in your functionality 
           }
      });
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从云功能中的 firestore 获取文档 - How to get a document from firestore in cloud functions 如何使用 StreamBuilder 显示我的 Cloud firestore 数据库中一个特定文档的数据? - How do I use StreamBuilder to display the data from ONE specific document in my Cloud firestore database? Firestore接管一分钟搞定里面的文档 Firebase Cloud Function - Firestore take over a minute to get a document inside Firebase Cloud Function 将数据从 Google Cloud 保存到 Firestore Function - Saving data to Firestore from Google Cloud Function 无法获取 Cloud Function 以从 Google Cloud IoT Pub/Sub 主题获取数据并将其存储在 Firestore 数据库中 - Cannot get a Cloud Function to fetch data from Google Cloud IoT Pub/Sub topic and store it in a Firestore Database 如何在将数据作为实时数据库添加到 Cloud Firestore 之前获取 Cloud Firestore 文档的唯一 ID - How to get cloud firestore document unique Id before adding data to cloud firestore as Realtime database 如何从 flutter 中 user.uid 等于文档 ID 的 Cloud firestore 获取数据? - how to get data from cloud firestore where user.uid equal to document id in flutter? 无法从 flutter Cloud firestore 获取一份文件 - Can't get one document from flutter cloud firestore 在 React 中从 firebase Cloud Firestore 获取数据 - get data from firebase cloud firestore in react Cloud Firestore 文档添加给出错误“参数“数据”的值不是有效的 Firestore 文档。不能使用“未定义”作为 Firestore 值” - Cloud Firestore document add gives error "Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM