![](/img/trans.png)
[英]Firestore document is read multiple times after a single update in Firebase emulator
[英]Firebase Function query and update a single Firestore document
我正在尝试使用查询从 Firebase Function 更新用户的 firestore 文档,但在使其正常工作时遇到问题。 我的 Function 代码如下:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
/**
* A webhook handler function for the relevant Stripe events.
*/
// Here would be the function that calls updatePlan and passes it the customer email,
// I've omitted it to simplify the snippet
const updatePlan = async (customerEmail) => {
await admin.firestore()
.collection('users').where('email', '==', customerEmail).get()
.then((doc) => {
const ref = doc.ref;
ref.update({ 'purchasedTemplateOne': true });
});
};
运行查询时,我在 firebase 日志中收到以下错误:
完成的异常 function:TypeError:无法读取未定义的属性(读取“更新”)
任何关于我可能做错了什么的帮助或关于如何实现这一目标的建议将不胜感激,提前谢谢你!
更新:
通过对 Firestore 查询的更多理解,我能够解决我的问题:
const updatePlan = (customerEmail) => {
const customerQuery = admin.firestore().collection("users").where("email", "==", customerEmail)
customerQuery.get().then(querySnapshot => {
if (!querySnapshot.empty) {
// Get just the one customer/user document
const snapshot = querySnapshot.docs[0]
// Reference of customer/user doc
const documentRef = snapshot.ref
documentRef.update({ 'purchasedTemplateOne': true })
functions.logger.log("User Document Updated:", documentRef);
}
else {
functions.logger.log("User Document Does Not Exist");
}
})
};
错误消息告诉您doc.ref
未定义。 object doc
上没有属性ref
。
这可能是因为您误解了 Firestore 查询产生的 object。 即使您期望的是单个文档,过滤查询也可以返回零个或多个文档。 这些文档始终以 object 类型的QuerySnapshot 表示。 这就是doc
实际上是什么 - 一个 QuerySnapshot - 所以你需要这样对待它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.