How to use wildcards in firestore cloud functions?

Viewed 3655

I'm trying to use a wildcard in a cloud function with firestore like this:

exports.function_name= functions.https.onRequest((req, res) => {
return admin.firestore().collection('users/messages/{messageCollectionId}')

but it does not work. It works if I use an actual id, instead of the wildcard. Any help will be much appreciated.

2 Answers

There are no wildcards in Firestore paths to documents. You have to identify collections and documents by their IDs. If you need to find some documents based on some property, you'll need to do a query using some field value as a filter.

You might be confused by wildcards in Cloud Functions trigger paths. When you define a Firestore trigger function, you can use a wildcard to determine which documents would trigger that function, but you can't use them with the client SDKs to locate documents.

I'm not sure what do you want to do. But you DO can use wildcards like this:

You can use wildcard on Firebase functions by accessing on context.

exports.function_name= functions.firestore.document('users/messages/{messageCollectionId}').onCreate((snap, context) => {
  const messageCollectionId = context.params.messageCollectionId;
  console.log('my messageCollectionId: ${messageCollectionId});
});

In your example I don't know why would you use wildcard. Isn't just a var variable?

exports.function_name= functions.https.onRequest((req, res) => {
  const messageCollectionId = req.params.id;
  admin.firestore().collection('users/messages/${messageCollectionId}')
});

Read more: https://cloud.google.com/firestore/docs/extend-with-functions

Related