Node.js Firebase云函数获取更新的文档详细信息
我正在尝试编写一个云函数,如果我的应用程序更改了用户firestore数据库中的一些字符串。云函数需要发送推送通知。数据库体系结构是Messages=>{UID}=>UpdatedMessages。问题是我无法确定如何检索哪个updateMessage下更新了UIDNode.js Firebase云函数获取更新的文档详细信息,node.js,firebase,google-cloud-firestore,google-cloud-functions,Node.js,Firebase,Google Cloud Firestore,Google Cloud Functions,我正在尝试编写一个云函数,如果我的应用程序更改了用户firestore数据库中的一些字符串。云函数需要发送推送通知。数据库体系结构是Messages=>{UID}=>UpdatedMessages。问题是我无法确定如何检索哪个updateMessage下更新了UID const functions = require('firebase-functions'); const admin = require('firebase-admin') admin.initializeApp() con
const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp()
const toUpperCase = (string)=> string.toUpperCase()
var registrationToken = 'dfJY6hYzJyE:APdfsdfsdddfdfGt9HMfTXmei4QFtO0u1ePVpNYaOqZ1rnDpB8xfSjx7-G6tFY-vWQY3vDPEwn_iZVK2PrsGUVB0q9L_QoRYpLJ3_6l1SVHd_0gQxJb_Kq-IBlavyJCkgkIZ';
exports.sendNotification = functions.firestore
.document('messages/{userId}/{updatedMessage}')
.onUpdate((change, context) => {
var message = {
data: {
title: 'Update',
body: 'New Update'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent messagesssss:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
});
我只需要从UID重新输入“var registrationToken” 您必须使用
context
对象的params
属性,如下所示
exports.sendNotification = functions.firestore
.document('messages/{userId}/{updatedMessage}')
.onUpdate((change, context) => {
const userId = context.params.userId;
const updatedMessage = context.params.updatedMessage;
var message = {
data: {
title: 'Update',
body: updatedMessage //For example, use the value of updatedMessage here
},
//...
};
//IMPORTANT: don't forget to return the promise returned by the asynchronous send() method
return admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent messagesssss:', response);
return null;
})
.catch((error) => {
console.log('Error sending message:', error);
return null;
});
});
有关更多信息,请参阅和
关于上述代码中注明为“重要”的备注,您可以在此处观看官方Firebase视频系列:。特别是看三个名为“学习JavaScript承诺”的视频(第2部分和第3部分特别关注后台触发的云函数,但之前确实值得看第1部分).如果您已经想触发云函数,为什么不首先调用云函数对数据库进行写操作呢?我知道您正在使用firestore,但这可能会有帮助,谢谢您Constantin Beer。我想我会使用云函数在我的数据库上写东西。这样发送推送通知就更容易了。显示您无法确定编辑了哪条消息?只需在
/messages/
节点下的onEdit
处触发您的函数,您就可以获得编辑过的消息@Emanuele的整个路径,谢谢您不知道这是可能的