简体   繁体   中英

Query a reference field in Firestore document

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);
      });
});

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);
      });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM