Reputation: 282
I am trying to send personalised push notifications to all users at a specific time each day. The method I have for sending these is:
Google Cloud Scheduler > Cloud Pub/Sub > Cloud Function > Cloud Messanging > Push notification
This works well for generic messages but I want to personalise them - this means I need to access data within the specific user's subcollections such as users/userID/products/product1
.
As described here there is no way to directly get the user ID using the Pub/Sub trigger - so what I am trying to do is create a second function that will trigger a generic document to be created for every user, then use that as a trigger for personalised notification as such:
Cloud Scheduler > Cloud Pub/Sub > 1st Function creates document for every user > 2nd Function triggers personalised push notification
The problem I am having is I cannot work out how to create a generic document for every user using a function, I have tried this:
exports.addNotificationsDocumentFunction = functions
.pubsub
.topic('notificationDocuments')
.onPublish((message, context) => {
console.log(message);
console.log('The function was triggered at ', context.timestamp);
console.log('The unique ID for the event is', context.eventId);
var data = {
createdAt : context.timestamp.toString
}
return admin.firestore()
.collection('users')
.doc({userID})
.collection('userNotifications')
.doc('latestNotification')
.set(data)
.catch(error => {
console.log('Error writing document: ' + error);
return false;
});
});
I get the following error:
ReferenceError: userID is not defined
at exports.addNotificationsDocumentFunction.functions.pubsub.topic.onPublish (/srv/index.js:51:19)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:132:23)
at /worker/worker.js:825:24
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
Is it possible to use Google Cloud Functions to create a document for every user?
OR is there generally a better method for sending a daily push notification with personalised data from Firestore?
Upvotes: 1
Views: 116
Reputation: 317487
Firestore does not have wildcards for creating, updating, or deleting multiple documents at the same time. If you have a list of user documents, and you want to do something for each user, you have to query that collection, iterate the documents, and perform the work for each individual user. So,
Upvotes: 2