使用Google Cloud Functions从另一个Firestore集合中引用的字段在Firestore集合中创建字段

问题描述 投票:0回答:1

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

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个回答
0
投票

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

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

// First get the artist doc
return artistRef.get().then(doc => {
    return event.data.ref.set({
        // use the properties of the doc in here
    })
})
© www.soinside.com 2019 - 2024. All rights reserved.