Skip to content
Advertisement

How to do CRUD operations on a firestore DB from a cloud function? (Node.js)

I use a cloud function as a webhook receiver, so every time I get a webhook I want to update firestore with some data for example. I don’t get how to use firestore in my clound function.

I tried this:

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

      res.send(admin.database().ref("/tmp_list/1uMW9ED3YGMfERHZiKJc").get());

All do not seem to be able to initilise this. I also tried:

 admin.initializeApp(functions.config().firebase);

Advertisement

Answer

As explained in the documentation, the following should do the trick:

const functions = require('firebase-functions');

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

Then, to interact with the Realtime Database in an HTTPS Cloud Function you should do along the following lines:

exports.date = functions.https.onRequest(async (req, res) => {
  const db = admin.database();

  const dataSnapshot = await db.ref("tmp_list/1uMW9ED3YGMfERHZiKJc").get();

  const data = dataSnapshot.val();

  // ... 

  res.send(data);
});

Since you tagged your question as google-cloud-firestore, note that in order to interact with Firestore in an HTTPS Cloud Function you should do as follows:

exports.date = functions.https.onRequest(async (req, res) => {
  const db = admin.firestore();

  const docSnapshot = await db.doc("tmp_list/1uMW9ED3YGMfERHZiKJc").get();

  const data = docSnapshot.data();

  // ... 

  res.send(...)
});

I recommend you watch the following official video.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement