Home > Mobile >  Accessing Firestore Document data within JavaScript https on request function
Accessing Firestore Document data within JavaScript https on request function

Time:07-27

I am working on a piece of my app where I need to make a call to a Firebase Function, which parses through Firestore data to return a dictionary that I will use to populate UI in Swift.

My function is declared as so: exports.getUIBetData = functions.https.onRequest( (request, response) => {

This function takes in a userID as body parameter. Then, I need to hit firebase to get a specific document's data tied to this userId and perform some actions on it. I believe I am running into some issues with the async functionality behind getting data from a document, as I keep getting errors or simple promises that haven't been resolved. Here is my query:

const body = request.body;
const userId = body.data.userId;
  const bettorIdDoc = admin.firestore()
      .collection("user_dim").doc(userId).get().data();

I can confirm that "user_dim" is a valid collection, and the userId is a key to a document within it. However, I can't access the fields tied to this doc.

I was originally trying with just .data(), and realized from the official documentation that you need to do .get().data(), however this is async. How do I handle the async nature when I am attempting to do this within my main function (exports.getUIBetData = functions.https.onRequest( (request, response) => {)?

Error: TypeError: admin.firestore(...).collection(...).doc(...).get(...).data is not a function

CodePudding user response:

Loading data from Firestore (and pretty much any cloud API) is an asynchronous operation. You can see this by checking the return type of get(), which is Promise<DocumentSnapshot> and not just DocumentSnapshot.

This means you'll have to use then or await (if you're in an async context) to be able call data():

const bettorIdRef = admin.firestore()
   .collection("user_dim").doc(userId)
ref.get().then((snapshot) => console.log(snapshot.data());
  • Related