I am having trouble making a javascript code that will send a notification to the user. I have few questions and clarifications that I want to know:
TypeError: Cannot read property 'userID' of undefined
at exports.sendNotification.functions.firestore.document.onWrite.event (/srv/index.js:8:30)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
at /worker/worker.js:825:24
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
tokenID
, how will i implement it? One time insertions when the user sign up? or Every time the user logged in the token id will updated?Below is my code on index.js:
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.firestore.document("Buyers/{userID}/Notifications/{notificationId}").onWrite(event => {
const userID = event.params.userID;
const notificationId = event.params.notificationId;
console.log("BuyerID: "+userID);
return admin.firestore().collection("Buyers").doc(userID).collection("Notifications").doc(notificationId).get().then(queryResult => {
const notificationMessage = queryResult.data().notificationMessage;
const notificationTitle = queryResult.data().notificationTitle;
console.log("Title: "+notificationTitle);
console.log("Message: "+notificationMessage);
const toUser = admin.firestore().collection("Buyers").doc(userID).get();
return Promise.all(toUser).then(result => {
const tokenId = result[0].data().tokenId;
const notificationContent = {
notification: {
title: notificationTitle,
body: notificationMessage,
icon: "default",
sound : "default"
}
};
return admin.messaging().sendToDevice(tokenId, notificationContent).then(result => {
console.log("Notification sent!");
return null;
});
});
})
});
And here is the sample structure of my database in firestore
You're using a very old syntax for Cloud Functions triggers. The APIs changed since the beta release years ago. Update your code to the newer signatures as shown in the documentation for Firestore triggers . Triggers now receive two arguments instead of one.
exports.sendNotification =
functions.firestore.document("Buyers/{userID}/Notifications/{notificationId}")
.onWrite((change, context) => {
const userID = context.params.userID;
const notificationId = context.params.notificationId;
console.log("BuyerID: "+userID);
If you're following an old tutorial, please notify the author of the tutorial to update it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.