在Firestore字段中自动生成字段

时间:2017-12-15 20:06:08

标签: firebase google-cloud-firestore

在“show”集合中的Firestore文档中,我有两个字段:“artist”和“date”。创建一个名为“name”的新字段的最佳方法是什么,该字段结合了“artist”和“date”字段。

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

例如,假设“artist”=“Pink Floyd”和“date”=“19650303”。然后“名字”应为“19650303_pinkfloyd”。

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

我可以在HTML中组合这些字段。但我希望它存储在Firestore数据库中,以便我可以在其他应用程序中调用该字段。如果“艺术家”或“日期”字段发生变化,我显然希望更改“名称”字段。

Google Cloud Functions会处理这件事吗?

1 个答案:

答案 0 :(得分:0)

这是我为了让它在Google云端功能中运行而编写的功能。我很想知道这是否是实现这一目标的最佳方式,或者是否可以采用更好的方式。

// 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});
  });
相关问题