1
votes

In a Firestore document in a 'shows' collection, I have two fields: "artist" and "date". What is the best way to create a new field called "name" which combines the "artist" and "date" fields.

{
  "artist": "Pink Floyd",
  "date": "19650303"
}

For example, lets say "artist" = "Pink Floyd" and "date" = "19650303". Then "name" should be "19650303_pinkfloyd".

{
  "artist": "Pink Floyd",
  "date": "19650303",
  "name": "19650303_pinkfloyd"
}

I can combine thee fields in the HTML. But I want it stored in the Firestore database so that I can call on that field in other apps. And I obviously want the "name" field to change if either the "artist" or the "date" field are changed.

Is this something Google Cloud Functions would handle?

1

1 Answers

0
votes

Here's the function that I wrote to get it to work in Google Cloud Functions. Id love to hear if this the best way to accomplish this or if it can be done a better way.

// new name version that combines two variables in the event data to create a newnamee
exports.createnewshowname = functions.firestore
  .document('shows/{showId}')
  .onWrite(event => {
    // Get an object representing the document
    // e.g. {'name': 'pinkfloyd', 'venue': 'stubbs'}
    var newValue = event.data.data();
    // access a particular field as you would any JS property
    var name = newValue.name;
    var venue= newValue.venue;
    var newname = name+"_" +venue
    // You must return a Promise when performing asynchronous tasks inside a Functions such as
    // writing to the Firebase Realtime Database.
    // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
    return event.data.ref.set({
      newname: newname
    }, {merge: true});
  });