Home > Back-end >  Get data from firestore document and use in cloud function
Get data from firestore document and use in cloud function

Time:06-29

In the user's collection, each user has a document with a customer_id. I would like to retrieve this customer_id and use it to create a setup intent.

The following code has worked for me in the past. However, all of a sudden it throws the error:

Object is possibly 'undefined'

The error is on the following line under snapshot.data() in this line:

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 :)

CodePudding user response:

this is because snapshot.data() may return 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

CodePudding user response:

I can see you are using a sub collection order,You need to loop through the snapshot data using the forEach loop.


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

Try this out but.

CodePudding user response:

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:

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;
  ...
}
  • Related