I created a firebase function to test how to get data from a firebase function. However, I am not able to get any data.
Note: I have another function that is listing all user from Authentication without any problem.
Here is my code:
import {onRequest} from "firebase-functions/v2/https";
import * as logger from "firebase-functions/logger";
import * as admin from "firebase-admin";
const serviceAccount = require('../serviceAccountKey.json');
// Initialize Firebase Admin SDK
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const db = admin.firestore();
export const listUserProfiles = onRequest(async (request, response) => {
response.set('Access-Control-Allow-Origin', '*');
try {
const ref = db.collection("UserProfiles").doc("cnZbRQtnCnQ52kTbcxI6Zq7d3VA3");
const docSnap = await ref.get();
if (docSnap.exists) {
console.log("Document data:", docSnap.data());
response.status(200).json(docSnap.data());
} else {
console.log("No such UserProfiles!");
response.status(200).json({});
}
}
catch(error) {
console.log('Error Getting profile:', error);
response.status(500);
response.statusMessage = `Error Getting profile: ${JSON.stringify(error)}`;
response.send(error);
}
})
When I hit the endpoint the log is showing No such UserProfiles!
I have a firestore rules that allow read for this collection.
I already checked the document cnZbRQtnCnQ52kTbcxI6Zq7d3VA3
and it is exists on the collection
Why I am not getting data?
I am expecting return the content of the document
2
Answers
I found the problem, shame on me. I was running the emulator and I found out there was no data on it.
After pushing it into the cloud the data shows up.
I am not sure about the keyword
exists
can you try to checkdocSnap.data()
insteadalso add
databaseURL
in youradmin.initializeApp