2
votes

I am trying to write a function that will, after data in a document (within a Firestore 'artists' collection) is changed, will have Google Cloud Functions find all the documents in another collection ('shows') that have a reference field ('artist') that points to the document (within the 'artists' collection) that was just changed.

I can't seem to figure out how to query the reference field. Ive tried everything from using the ID of the artist document, to the path, to the full URL. But I get an error in the Google Cloud Function console:

Error getting documents Error: Cannot encode type ([object Undefined]) to a Firestore Value

Here's a sample of my code:

exports.updateReferenceArtistFields = functions.firestore
  .document('artists/{artistId}').onWrite(event => {
  var artistRef = event.data.data();
  var artistId = artistRef.id;
  var ShowsRef = firestore.collection('shows');
  var query = ShowsRef.where('artist', '==', artistId).get()
      .then(snapshot => {
          snapshot.forEach(doc => {
              console.log(doc.id, '=>', doc.data());
          });
      })
      .catch(err => {
          console.log('Error getting documents', err);
      });
});
1

1 Answers

0
votes

I would get the artistId from the params directly like this:

var artistId = event.params.artistId;

Example:

exports.updateReferenceArtistFields = functions.firestore
  .document('artists/{artistId}').onWrite(event => {
  var artistId = event.params.artistId;
  var showsRef = firestore.collection('shows');
  var query = showsRef.where('artist', '==', artistId).get()
      .then(snapshot => {
          snapshot.forEach(doc => {
              console.log(doc.id, '=>', doc.data());
          });
      })
      .catch(err => {
          console.log('Error getting documents', err);
      });
});