Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a firestore query inside a Firebase function?

I have a firestore query inside my firebase function that is used to retrieve a document if it has a specific value inside it (eg: if the name field is equal to "name"). I have written the code and declared the function as a functions.https.onCall so I can call it within my app. Calling the function works however it doesn't do anything when it has started. Here is the query that I have written that is causing the problem:

let query = admin.firestore().collection('...').where('...', '==', value).orderBy('...').limit(1);
        query.get().then(snapshot => {
            let ... = snapshot[0];

Here is my function declaration:

exports.functionName = functions.https.onCall((data, context) => {

What the function should do is log what was passed into it from the calling code, perform the query (currently testing with valid data), and continue with the rest of the function. Right now it doesn't do anything but when I remove the where function it works but cannot get the specific document I am looking for. Thank you for any insights into my problem.

like image 543
Liam Avatar asked Apr 23 '26 09:04

Liam


1 Answers

I had a similar need and found this question when searching for an example. This worked for me:

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

exports.doQuery = functions.https.onRequest(async (req, res) => {

  var query = await admin.firestore().collection('COLLECTION_NAME')
    .where('FIELD_NAME', '==', 'FIELD_VALUE')
    .get().then(result => {
        result.forEach((doc) => {
            console.log(doc.id, doc.data());
        });
    });
}

A few things tripped me up when I was trying to piece this together on my own:

  • In a cloud function you get the firestore interface from the admin interface. Call admin.firestore() to get it.
  • Any number of errors or compilation errors will crash the emulator, and when the emulator stops your test data goes away. So if you're trying this with the emulator remember you need to re-create your test data whenever you restart it.
like image 142
moof2k Avatar answered Apr 25 '26 22:04

moof2k