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

Javascript Firebase数据库触发器-从快照获取数据库对象,javascript,firebase,firebase-realtime-database,google-cloud-firestore,google-cloud-functions,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('/not

我正在编写一个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

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

const snapshotRef = snapshot.ref.root;
let batch = admin.firestore().batch();
看到和

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

因此,如果您想在云函数中创建一个应用程序,您需要从Admin SDK获取它,如下所示:

const snapshotRef = snapshot.ref.root;
let batch = admin.firestore().batch();

参见

非常感谢@Renaud!我无意中阅读了Firestore文档:将使用snapshot.ref.root用于其他目的!