我需要有关Firestore功能的帮助。我正在开发一个需要通知的应用程序,并且我正在使用Firebase作为后端,我对云功能特性是全新的。
所以我想在将文档添加到集合中时向用户发送通知,我尝试为该功能设置一些内容,但由于我不知道的原因而无法正常工作,我的Node Js是更新版本,firebase工具已更新,但我仍然收到错误。
这是我的index.js文件和错误消息。感谢您的帮助。
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.firestore.document('Users/{userId}/Notifications/{notificationId}').onWrite((change, context) =>{
const userId = context.params.userId;
const notificationId = context.params.notificationId;
console.log('The User id is : ', userId);
if(!context.data.val()){
return console.log('A notification has been deleted from the database');
}
// ref to the parent document
const device_token = admin.firestore.doc('Users/${userId}/Token/${userId}/deviceToken').once('value');
return device_token.then(result => {
const token_id = result.val();
const payLoad = {
notification:{
title: "Qubbe",
body: "You have a new comment!",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payLoad).then(response => {
console.log('This is the notification feature');
});
});
device_token.catch(error => {
console.log(error);
});
});
错误:
Scrrenshot to error in command line
最佳答案
由于您使用的是以下语法onWrite((change, context)...)
,因此我假设您使用的是Cloud Functions版本> = 1.0。
对于版本> = 1.0,您应该不带任何参数地初始化firebase-admin
,如下所示:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
见https://firebase.google.com/docs/functions/beta-v1-diff#new_initialization_syntax_for_firebase-admin