11

Assuming that I trigger events on the following ref('/users/{userId}/items/{newItem}') I want to get a value from inside the wildcard userId

I have tried var token = event.params.userId.token but it return to be undefined

Any suggestions?

Nour Eldin Ahmed
  • 273
  • 5
  • 14
  • 2
    In your code snippet only `event.params.userId` will be defined. There is no magic lookup of the user with that ID happening. If you want to get the user object of the user that triggered the function, see https://stackoverflow.com/questions/42750060/getting-the-user-id-from-a-database-trigger-in-cloud-functions-for-firebase – Frank van Puffelen Dec 19 '17 at 15:41
  • Thanks a lot, I've tried this snippet of code and it worked just fine: ` return admin .database() .ref(`/users/${userId}/token`) .once('value') .then(data => { return admin.messaging().sendToDevice(data.val(), payload); });` where I triggered a single value for the wildcard userId to get its token – Nour Eldin Ahmed Dec 19 '17 at 16:43
  • That snippet looks up the token in the database based on the `userId`. But you can't just read the token by doing `event.params.userId.token`, that `token` property simply isn't available on a parameter from the path that triggered the function. – Frank van Puffelen Dec 19 '17 at 17:14

3 Answers3

6

In firestore you can use this.

exports.getUser = functions.firestore
    .document('users/{userId}').onWrite((change, context) => {
        let userId = context.params.userId;
        //...
    });
elbert rivas
  • 1,464
  • 1
  • 17
  • 15
4

Token is not a parameter returned automatically from trigger events. In trigger wild cards only parameters corresponding directly to the wildcard are returned. So You need to do the following if you want to use the

var userId = event.params.userId

And then inside the function you can make another Promise

return admin.database().ref(/users/userId/token).once('value').then(data => { 
//do something here
 })

This will help you get the token. Or if you want to do it in one step, you can try the following with userID as wild card.

return admin.database().ref(/users/{userId}/token).once('value').then(data => { 
    //do something here
     })

But here you will receive multiple tokens and then you will have to iterate through the children to decide which userId is of relevance to you

Abhishek
  • 1,261
  • 1
  • 13
  • 30
1

You can find wildcard values like this

wildCardValue = context.params.wildCardName