Ad

Firebase Database Trigger - Get Database Object From Snapshot

I am writing a Firebase database trigger function to push notifications to several users. For consistency I would like to batch all write operations, but I am having trouble creating the batch.

How can I get a reference to the database from data snapshot?

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

exports.onNoteCreate = functions
.region('europe-west1')
.database
.ref('/notes/{noteId}')
.onCreate((snapshot, context) => {
  //Get a reference to the database - this does not work!
  const db = snapshot.getRef()
  ...
  const notificationObject = {"test": true}
  //Run database batched operation - prepare batch
  let batch = db.batch()
  peopleToAlert.forEach((personId, index) => {
    //Write notification to all affected people
    const notificationId = db.ref().push()
    const batchWrite = db.collection(`/notifications/${personId}/notes`).doc(notificationId)
    batch.set(batchWrite, notificationObject)
  })
  //Commit database batch operation
  return batch.commit().then(() => {
    return new Promise( (resolve, reject) => (resolve()))
  }).catch( (err) => {
    return new Promise( (resolve, reject) => (reject(err)))
  })
})

I have also tried the approach below to no avail

const db = admin.database()

Any clarification much appreciated! Kind regards /K

Ad

Answer

To get the root Reference of the Database from a DataSnapshot, do as follows:

const snapshotRef = snapshot.ref.root;

See https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#ref and https://firebase.google.com/docs/reference/js/firebase.database.Reference.html#root


HOWEVER, you are triggering your Cloud Function with a Realtime Database trigger while the concept of batched write is for Firestore, which is a different database service. So you cannot use the root Reference of the Realtime Database to create a Firestore WriteBatch.

So if you want to create a WriteBatch within your Cloud Function you need to get it from the Admin SDK, as follows:

let batch = admin.firestore().batch();

See https://firebase.google.com/docs/reference/admin/node/admin.firestore

Ad
source: stackoverflow.com
Ad