[英]Checking with Cloud Function if a database node exists in Firebase Realtime Database
I have a onUpdate Cloud Function and I need to check if a database node exists. 我有一个onUpdate云功能,我需要检查数据库节点是否存在。
For my the ideal way to do it would be: 对我而言,理想的做法是:
exports.watchTeamMemberUpdates = functions.database
.ref('/teams/{teamName}')
.onUpdate((change) => {
if (!change.before.exists()) {
console.log('exists error');
return null;
}
});
But it requires a snapshot and i'm giving it a promise. 但它需要一个快照,我正在给它一个承诺。
Is it possible to check if the file exists with the promise in any way? 是否可以以任何方式检查文件是否存在承诺?
Also is there a better way to make snapshots other than .once.then? 还有更好的方法来制作除.once.then之外的快照吗?
I make the assumption that by writing "I need to check if a file exists" you mean checking if a database node exists (ie the team member saved under team name). 我假设通过编写“我需要检查文件是否存在”,您的意思是检查数据库节点是否存在(即团队成员是否以团队名称保存)。 I've taken the liberty to modify your question title and content accordingly.
我冒昧地相应地修改你的问题标题和内容。
Note that if you want to detect if the team member didn't exist with an onUpdate()
trigger, you will not succeed , because this Cloud Function will only be triggered if the node existed before , since we watch for updates (not for creation). 请注意,如果要检测团队成员是否不存在
onUpdate()
触发器, 则不会成功 ,因为只有节点存在之前才会触发此Cloud Function,因为我们会查看更新(而不是创建) )。
So you should probably use an onWrite()
trigger. 所以你应该使用
onWrite()
触发器。 Below is the code for the two types of trigger. 下面是两种触发器的代码。 I would suggest you try several writes and updates in your database (after having deployed theses two functions, of course) and look what is printed to the Cloud Function log.
我建议您在数据库中尝试多次写入和更新(当然,在部署了这两个函数之后)并查看打印到Cloud Function日志的内容。
exports.watchTeamMemberUpdates = functions.database
.ref('/teams/{teamName}')
.onUpdate((change, context) => {
if (!change.before.exists()) {
console.log('watchTeamMemberUpdates: exists error');
return null;
} else {
console.log('watchTeamMemberUpdates: Team member exists');
return null;
}
});
exports.watchTeamMemberWrites = functions.database
.ref('/teams/{teamName}')
.onWrite((change, context) => {
if (!change.before.exists()) {
console.log('watchTeamMemberWrites: exists error');
return null;
} else {
console.log('watchTeamMemberWrites: Team member exists');
return null;
}
});
PS: Note that the handler to be passed to the onUpdate(handler)
method is a function with two arguments, see https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onUpdate . PS:请注意,要传递给
onUpdate(handler)
方法的onUpdate(handler)
是一个包含两个参数的函数,请参阅https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onUpdate 。 However the second is optional. 然而,第二个是可选的。 This is the same with the
onWrite(handler)
method. 这与
onWrite(handler)
方法相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.