我正在编写一个 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 获取数据库的根引用DataSnapshot
,请执行以下操作:
const snapshotRef = snapshot.ref.root;
请参阅https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#ref和https://firebase.google.com/docs/reference/js/firebase.database.Reference.html#root
但是,您正在使用实时数据库触发器触发您的云功能,而批量写入的概念是针对Firestore 的,后者是一种不同的数据库服务。因此,您不能使用实时数据库的根引用来创建 Firestore WriteBatch
。
因此,如果您想WriteBatch
在您的 Cloud Functions 中创建一个,您需要从 Admin SDK 中获取它,如下所示:
let batch = admin.firestore().batch();
请参阅https://firebase.google.com/docs/reference/admin/node/admin.firestore
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句