Reputation: 9759
I have a messages
entry that looks like this:
firbaseapp
messages
-KiG85eYMH7jfKph4bl3
created: 1492788734743
title: "title"
message: "message"
I want to send a notification when new entries are added to this list so I added this cloud function:
exports.sendMessageNotification = functions.database.ref('/messages/').onWrite(event => {
event.data.forEach(message => {
if (message.val().notificationSent) {
return;
}
admin.messaging().sendToTopic(...)
.then(res => {
return db.ref('/messages').child(message.key).update({
notificationSent: (new Date()).getTime(),
});
})
});
});
Problem is message.key
is messages-KiG85eYMH7jfKph4bl3
so when I try to save it, it creates a new entry instead of updating the existing one:
firbaseapp
messages
-KiG85eYMH7jfKph4bl3
created: 1492788734743
title: "title"
message: "message"
-messages-KiG85eYMH7jfKph4bl3
notificationSent: 123434554534
What I wanted is for notificationSent
to be set on the existing entry.
I also tried using message.ref
but I get the same result.
So what is the best way to update a list item in firebase in a cloud function?
Upvotes: 2
Views: 1374
Reputation: 38289
I think this accomplishes what you want to do and also answers your questions in the comments:
exports.sendMessageNotification = functions.database.ref('/messages/{messageId}')
.onWrite(event => {
const messageId = event.params.messageId;
console.log('messageId=', messageId);
if (event.data.current.child('notificationSent').val()) {
console.log('already sent');
return;
}
const ref = event.data.ref; // OR event.data.adminRef
admin.messaging().sendToTopic(...)
.then(res => {
return ref.update({
// Caution: this update will cause onWrite() to fire again
notificationSent: (new Date()).getTime(),
});
})
});
Upvotes: 3