【发布时间】:2019-01-01 19:48:08
【问题描述】:
我正在尝试编写一个函数,该函数在用户收到新评论并发送通知时触发。评论存储在 /Users/{user_id}/Notifications/{notification_id} 中。用户将他们的设备通知令牌保存到 /users/{userID}
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotif = 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;
return admin.firestore().collection('Users').document(user_id).collection('Notifications').document(notification_id).get().then(queryResult=>{
const from_user_id = queryResult.data().From;
const from_data = admin.firestore().collection('Users').document(from_user_id).get();
const to_data = admin.firestore().collection('Users').document(user_id).get();
return Promise.all([from_data, to_data]).then(result => {
const from_name = result[0].data().From;
const to_name = result[1].data().From;
console.log("FROM: " + from_name + "TO: " + to_name);
});
});
});
这是 package.json 文件。一切都是最新的
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"firebase-admin": "^6.4.0",
"firebase-functions": "^2.1.0"
},
"private": true
}
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"firebase-admin": "^6.4.0",
"firebase-functions": "^2.1.0"
},
"private": true
}
Firebase 给出以下错误:
TypeError: Cannot read property 'from' of undefined
at Promise.all.then.result (/user_code/index.js:21:47)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
【问题讨论】:
-
您的代码始终使用
From(大写F),而错误消息提到from(小写f)。您确定这是引发错误的代码吗? -
我尝试了 F 的两种情况。如果使用大写 F,则错误对应于“From”,如果使用 f,则对应于“from”。
-
from_data = admin.firestore().collection('Users').document(from_user_id).get()文档似乎不存在。在调用from_data.data()之前,您需要检查if (from_data.exists)。
标签: node.js firebase google-cloud-firestore firebase-admin