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
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM