我正在尝试制作Firebase推送通知应用程序 并且在上传脚本时出现此错误。我不了解无法读取属性错误
TypeError: Cannot read property 'from' of undefined
at admin.firestore.collection.doc.collection.doc.get.then.queryResult
(/user_code/index.js:16:48)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
这是我的node.js脚本
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.firestore.document("Users/{user_id}/Notifications/{notification_id}")
.onWrite((change,context)=> {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log("User ID : " + user_id + " | Notification ID : " + notification_id);
return admin.firestore().collection("Users").doc(user_id).collection("NotificationsN").doc(notification_id).get().then(queryResult =>{
const from_user_id = queryResult.data().from;
const from_data = admin.firestore().collection("Users").doc(from_user_id).get();
const to_data = admin.firestore().collection("Users").doc(user_id).get();
return promise.all([from_data, to_data]).then(result =>{
const from_name = result[0].data().name;
const to_name = result[1].data().name;
console.log("FROM : " + from_name +" TO : " + to_name)
return null;
}).catch(error => {
console.error(error);
res.error(500);
});
}).catch(error => {
console.error(error);
res.error(500);
});
});
答案 0 :(得分:0)
您的代码中有一个错字,试图从子集合中读取文档:
return admin.firestore().collection("Users").doc(user_id).collection("NotificationsN").doc(notification_id).get().then(queryResult =>{
注意N
中的NotificationsN
吗?触发该功能的代码中不存在
functions.firestore.document("Users/{user_id}/Notifications/{notification_id}")
要解决该错误,只需删除结尾的N
,然后保留:
return admin.firestore().collection("Users").doc(user_id).collection("Notifications").doc(notification_id).get().then(queryResult =>{
但是请注意,整个操作是不必要的:您正在(重新)加载触发该功能的文档。该文档已通过change.after
传递到您的函数中,因此您不必重新加载它。您可以直接从那里直接使用它:
from_user_id = change.before.data().from;