【问题标题】:Firebase database trigger - get database object from snapshotFirebase 数据库触发器 - 从快照中获取数据库对象
【发布时间】:2019-12-18 23:08:20
【问题描述】:

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

【问题讨论】:

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


    【解决方案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


    但是,您正在使用 实时数据库触发器 触发 Cloud Function,而批量写入的概念适用于 Firestore,这是一个不同的数据库服务。因此,您不能使用实时数据库的根引用来创建 Firestore WriteBatch

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

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

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

    【讨论】:

    • 非常感谢@Renaud!我不小心阅读了 Firestore 文档。 :) 将 snapshot.ref.root 用于其他目的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2017-10-02
    • 2019-03-03
    • 2016-12-10
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多