【问题标题】:Creating a field in a Firestore collection from a field referenced in another Firestore collection using Google Cloud Functions使用 Google Cloud Functions 从另一个 Firestore 集合中引用的字段创建 Firestore 集合中的字段
【发布时间】:2017-12-20 15:01:05
【问题描述】:

我正在尝试在 Firestore 集合(“shows”)中创建一个字段(“artistName”),该字段是从另一个 Firestore 集合(“艺术家”)中的字段(“名称”)中提取的。 “shows”集合有一个引用字段(“artist”),它指向“artists”集合中的文档。要创建该字段,我使用 Google Cloud Functions。这是我的代码:

exports.addReferenceDataToCollection = functions.firestore
  .document('shows/{showId}').onWrite(event => {
  var newValue = event.data.data();
  var artistId = newValue.artist.id;
  var artistRef = firestore.collection('artists').doc(artistId);

  return event.data.ref.set({
    artistName: artistRef.get().then(doc => {
      if (!doc.exists) {
        console.log('No such document!');
      } else {
        console.log('Document data:', doc.data());
        var artistName = doc.data().name;
        console.log('Artist Name:', artistName);
        return Promise.resolve(artistName);
      }
    })
  }, {merge: true});
});

我似乎无法从承诺中获取数据。

【问题讨论】:

    标签: javascript firebase google-cloud-functions google-cloud-firestore


    【解决方案1】:

    你需要先做artistRef.get(),然后在你得到你需要的文档之后,使用它在event.data.ref.set()中的数据。正如您现在所写的那样,您将一个 Promise 对象分配给 artistName 属性。

    这种模式的一般形式如下:

    // First get the artist doc
    return artistRef.get().then(doc => {
        return event.data.ref.set({
            // use the properties of the doc in here
        })
    })
    

    【讨论】:

      猜你喜欢
      • 2021-05-06
      • 1970-01-01
      • 2022-01-19
      • 2020-10-17
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      相关资源
      最近更新 更多