我正在尝试在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});
});
我似乎无法从承诺中获取数据。
你需要先做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
})
})