import * as functions from 'firebase-functions';
console.log('I am a log entry0!');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
console.log('I am a log entry1!');
export const onMessageCreate = functions.database
.ref('/users/{userId}/totalScore')
.onUpdate((change) => {
console.log('I am a log entry2!');
//var a = admin.firestore().collection('/users');
})
我已经部署了该功能,并且可以在控制台中看到它。但是在数据库中更新totalScore
时不会执行该功能。...
答案 0 :(得分:1)
我认为更新是在ref上而不是在子项上检查的 试试这个
export const onMessageCreate = functions.database
.ref('/users/{userId}')
.onUpdate((change) => {
console.log('I am a log entry2!');
//var a = admin.firestore().collection('/users');
})
您可以在该位置获取快照的旧值和新值
答案 1 :(得分:1)
您的数据库为Firestore,但您使用的是由实时数据库中的更新触发的Cloud Function。这是两种不同的Firebase服务,您需要相应地更改代码。
以下代码将起作用:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.onMessageCreate = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
// Get an object representing the document
const newValue = change.after.data();
// ...or the previous value before this update
const previousValue = change.before.data();
if (newValue.totalScore !== previousValue.totalScore) {
console.log('NEW TOTAL SCORE');
}
return null;
//I guess you are going to do more than just logging to the console.
//If you do any asynchronous action, you should return the corresponding promise, see point 3 below
//For example:
//if (newValue.totalScore !== previousValue.totalScore) {
// return db.collection("score").doc(newValue.name).set({score: newValue.totalScore});
//}
});
请注意:
onUpdate
云功能。当Firestore文档的任何字段发生更改时,云功能将被触发。但是您可以检测到哪些字段已更改,如上面的代码所示。admin.initializeApp();
进行初始化,请参见https://firebase.google.com/docs/functions/beta-v1-diffList return null;
。 (有关这一点的更多详细信息,建议您观看Firebase视频系列中的有关“ JavaScript Promises”的3个视频:https://firebase.google.com/docs/functions/video-series/)。答案 2 :(得分:1)
如果您正在使用Cloud Firestore,则您的侦听器不正确。在您的情况下,您要为实时数据库指定一个侦听器。我们从函数中提取firestore并指定要在其上使用侦听器的文档的路径:
import * as functions from 'firebase-functions';
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
export const onMessageCreate = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
console.log(change.before.data()); // shows the document before update
console.log(change.after.data()); // shows the document after change
return;
})