Javascript Firebase云函数:如何使用通配符符号获取对文档的引用?
以下是我尝试使用Firebase云函数所做的:Javascript Firebase云函数:如何使用通配符符号获取对文档的引用?,javascript,node.js,firebase,google-cloud-firestore,google-cloud-functions,Javascript,Node.js,Firebase,Google Cloud Firestore,Google Cloud Functions,以下是我尝试使用Firebase云函数所做的: 收听“public_posts”集合下其中一个文档中的更改 说明“公共”字段中的更改是否从“真”变为“假” 如果为true,则删除触发该函数的文档 对于步骤1和2,代码很简单,但我不知道步骤3的语法。获取触发函数的文档引用的方法是什么?也就是说,我想知道下面空行的代码是什么: exports.checkPrivate = functions.firestore .document('public_posts/{postid}').onUpdate(
exports.checkPrivate = functions.firestore
.document('public_posts/{postid}').onUpdate((change,context)=>{
const data=change.after.data();
if (data.public===false){
//get the reference of the trigger document and delete it
}
else {
return null;
}
});
有什么建议吗?谢谢 如中所述:
对于onWrite
和onUpdate
事件,change
参数具有before和before属性
在田野之后。每一个都是一个DataSnapshot
因此,您可以执行以下操作:
exports.checkPrivate = functions.firestore
.document('public_posts/{postid}').onUpdate((change, context)=>{
const data=change.after.data();
if (!data.public) { //Note the additional change here
const docRef = change.after.ref;
return docRef.delete();
}
else {
return null;
}
});
更新以下卡罗琳娜·哈格格的评论: 如果要获取
postid
通配符的值,需要使用context
对象,如:context.params.postid
严格来说,您得到的是文档id,而不是它的
DocumentReference
。当然,基于此值,您可以使用admin.firestore().doc(`public_posts/${postid}`)重建DocumentReference
将给出与更改相同的对象。在.ref
之后,onUpdate侦听器返回一个更改
对象()
要获取更新的文档,请执行以下操作:
change.after.val()
要删除文档,请执行以下操作:
change.after.ref.remove()
这很好,但肯定还有一种方法可以使用通配符符号中的“posted”东西。。。?否则你为什么要给它起个名字@KarolinaHagegård当然,您可以使用上下文
对象,请看这个。Aaaaaaah,很好!:)“我喜欢这个。”卡罗里纳赫德你可以投另一个答案的赞成票;-)你还没有宣布“改变”。。。我猜您已经在更新的onUpdate
中命名了您的响应,但是由于可以命名任何东西,如果您明确地这样说就好了。:)