Firebase数据库触发器-从快照获取数据库对象

时间:2019-08-12 11:06:30

标签: javascript firebase firebase-realtime-database google-cloud-firestore google-cloud-functions

我正在编写Firebase数据库触发函数,以将通知推送给多个用户。为了保持一致性,我想批处理所有写操作,但是在创建批处理时遇到了麻烦。

如何从数据快照获取对数据库的引用?

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)))
  })
})

我也尝试了以下方法无济于事

const db = admin.database()

任何澄清,不胜感激!问候/ K

1 个答案:

答案 0 :(得分:1)

要从DataSnapshot获取数据库的根引用,请执行以下操作:

const snapshotRef = snapshot.ref.root;

请参见https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#refhttps://firebase.google.com/docs/reference/js/firebase.database.Reference.html#root


如何,您正在使用实时数据库触发器触发云功能,而批量写入的概念是针对 Firestore 的。不同的数据库服务。因此,您不能使用实时数据库的根引用来创建Firestore WriteBatch

因此,如果要在Cloud Function中创建WriteBatch,则需要从Admin SDK中获取它,如下所示:

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

请参见https://firebase.google.com/docs/reference/admin/node/admin.firestore