[英]How to update a sub-collection document when sub sub-collection is created in firestore using cloud functions typescript
我有这个功能,旨在在创建子评论时更新评论的 commentsCount 字段,但它不起作用,我不知道为什么。 我点击了要更新的正确文档 ID,但我不知道为什么它不更新。 它虽然没有任何错误。 控制台正常运行并显示:`i 函数:开始执行“onCreateSubComment”
1d0HczjEvZM0T4u9iXb0 1d0HczjEvZM0T4u9iXb0 i 功能:在 ~1s 内完成“onCreateSubComment”
//this is working perfectly fine export const onCreateComment = functions.firestore.document("posts/{postId}/comments/{commentId}").onCreate(async (snap, context)=> { const postRefId = context.params.postId; const snapRef = snap.ref; const commentCollectionRef = snapRef.parent; const postRef = commentCollectionRef.parent; const postId = postRef?.id; try { return await db.collection("posts").doc(postId?? postRefId).update({commentsCount: admin.firestore.FieldValue.increment(1)}); } catch (e) { functions.logger.log(e); throw e; } });
//not working export const onCreateSubComment = functions.firestore.document("posts/{postId}/comments/{commentId}/subComments/{subCommentId}").onCreate(async (snap, context) => { const commentRefId = context.params.commentId; const postId = context.params.postId; const snapRef = snap.ref; const subCommentCollectionRef = snapRef.parent; const commentRef = subCommentCollectionRef.parent; const commentId =commentRef?.id; console.log(commentId); console.log(commentRefId); try { return await db.collection("posts").doc(postId).collection("comments").doc(commentId?? commentRefId ).update({commentsCount: admin.firestore.FieldValue.increment(1)}); } catch (e) { functions.logger.log(e); throw e; } });
您需要将字段名称放在引号之间,因此不要使用commentsCount
,而是使用"commentsCount"
,例如:
db.collection("posts").doc(postId).collection("comments")
.doc(commentId ?? commentRefId )
.update({"commentsCount": admin.firestore.FieldValue.increment(1)});
此外,我宁愿使用带有选项的set
merge: true
而不是update
。 这样其他字段就不会受到影响。 像这样:
db.collection("posts").doc(postId).collection("comments")
.doc(commentId ?? commentRefId )
.set({"commentsCount": admin.firestore.FieldValue.increment(1)
}, {merge: true});
我解决了。 代码没有任何问题。 它只是与我的其他功能相冲突。 感谢那些花时间提供帮助的人。 你们都很棒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.