我正在使用onSnapshot
在Firestore中收听收藏集。每次我从Python后端添加一些数据时,这些数据都会反映在Firebase控制台中,而不反映在我的UI中。
我正确地检查了我是否在侦听正确的集合,并且我的回调正确,以下是我的代码。当我删除change.type
时,querySnapshot
首先给我空的更改数据,然后再给我从后端添加的数据。
from google.cloud import firestore
db = firestore.Client.from_service_account_json(CREDENTIALS_FILE)
collection_name = 'mycollection'
collection_ref = db.collection(collection_name)
message = {
'data': 'testing'
}
collection_ref.add(message)
function subscribe_to_notifs(collection_name) {
var firestore_db = firebase.firestore();
var collection_ref = firestore_db.collection(collection_name);
const handleActivitySubscriptionWithInvocation = countFunctionInvocation(handleActivitySubscription, 1);
collection_ref.onSnapshot(handleActivitySubscriptionWithInvocation);
}
function handleActivitySubscription(querySnapshot) {
querySnapshot.docChanges().forEach(function(change) {
console.log(change.doc.data()); // Here I get the data
if(change.type === 'added') {
console.log(change.doc.data()); // Here I get an empty response i.e {}
}
});
}
/*
Firestore onSnapshot() sends initial payload which I don't want.
I only need to listen for updates in a collection
This function will make sure that the `subscription_function` is called 2nd time,
so that we get only the updates from a collection.
*/
function countFunctionInvocation(subscription_function, invoke_before_execution) {
var count = 0;
return function (args) {
count++;
if (count <= invoke_before_execution) {
return true;
}
else {
return subscription_function(args, count);
}
};
}
我希望change.doc.data()
中有一些数据。可能是什么原因?
注意:最初我的收藏夹中没有文档,当我获取一些数据时,我使用Python Admin SDK将其放入Firestore。