javascript - 如何使用 firebase 函数从 firestore 检索文档并从另一个 firestore 文档添加新数据?
问题描述
我是firebase云功能的新手,在firebase函数中从firestore文档中获取()和设置()数据时遇到了一些麻烦。
这是我在firebase函数中尝试做的事情:
- 在firestore中创建新文档“doc1”时访问其数据;
- 访问与“doc1”的“用户”字段关联的值;
- 该值属于“reference”类型,即指向另一个 Firestore 集合“col2/doc2”中的另一个文档的路径
- 使用此路径访问第二个文档“doc2”并检索属于该第二个文档的两个新值以将其添加到第一个文档“doc1”;
- 最终目标是将属于“doc2”的“name”和“city”字段的值添加到“doc1”;
到目前为止,我在这里尝试过,我确信我在语法和then()
链的使用方面几乎没有问题,但主要思想是:
exports.addDataFromDoc2ToDoc1 = functions.firestore
.document('col1/{doc1Id}')
.onCreate((change, context) => {
const doc1Id = context.params.doc1Id
const doc1 = change.data()
const refToDoc2 = doc1.refField
const doc2Data = refToDoc2.get()
.then(function (documentSnapshot) {
if (documentSnapshot.exists) {
doc2Data = documentSnapshot.data()
return doc2Data
}
})
const doc1Name = doc2Data.doc1Name
const doc1City = doc2Data.doc1City
db.collection('col1')
.doc(doc1Id)
.set({
name: doc1Name,
city: doc1City
});
})
我从 firebase 文档开始: https ://firebase.google.com/docs/functions/firestore-events
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.writeToFirestore = functions.firestore
.document('some/doc')
.onWrite((change, context) => {
db.doc('some/otherdoc').set({ ... });
});
如果有人可以帮助我完成这项任务,我将不胜感激,以及如何重组我的算法以提高效率?
非常感谢您的帮助和时间!
解决方案
由于该字段是Reference类型,所以需要使用对象的path
属性DocumentReference
,如下:
exports.writeToFirestore = functions.firestore
.document('col1/{doc1Id}')
.onCreate((snap, context) => {
const newValue = snap.data();
const refToDoc2 = newValue.refField;
return db.doc(refToDoc2.path).get()
.then((doc) => {
if (doc.exists) {
const name = doc.data().name;
const city = doc.data().city;
return snap.ref.update({ name, city })
} else {
throw new Error('No document corresponding to the Reference!')
}
})
.catch(error => {
console.log(error);
return null;
});
});
此外,请注意我们如何链接异步 Firestore 方法返回的承诺,非常重要的是,我们如何返回这个承诺链。
另请注意,我们使用的是update()
方法,而不是set()
一种。
推荐阅读
- c++ - 如何让用户等待才能再次使用某个功能?
- scala - 将 Akka HTTP 重定向到 HTTPS
- haskell - 从generics-sop的ConstructorInfo中提取嵌套类型信息
- mysql - 如何正确地将 mysql-query-results 解析为 typescript 对象
- log4j - 在 ignite 默认配置文件中添加 log4j 属性后,服务无法启动
- rust - 如何为 Substrate Runtime 实现 EVM Trait?
- python - 循环遍历列表并删除python中的某些元素时索引越界
- postgresql-11 - 您如何在 Postgresql 11 的存储过程的另一部分中使用别名和引用该别名?
- java - 设置与我的 GUI (Java Swing) 的自动交互之间的延迟
- node.js - 我正在使用 node.js 制作 API,并且我正在尝试通过在参数中传递事件的 id 来获取事件的详细信息