我想在firebase中创建一个云函数,每当用户第一次登录时,它就会被触发。 该函数需要将来自特定用户身份验证的UID添加到FireStore中一个特定的,已经存在的文档中。 问题是需要将UID添加到我不知道其位置的文档中。 我现在的代码没有完全做到这一点,但这是它出错的地方。 数据库简化后如下所示
organisations
[randomly generated id]
people
[randomly generated id] (in here, a specific document needs to be found based on known email
adress)
有多个不同的组织,用户属于哪个组织是未知的。 我想到使用通配符,如下所示:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
console.log('function ready');
//Detect first login from user
//if(firebase.auth.UserCredential.isNewUser()){
if(true){
//User is logged in for the first time
//const userID = firebase.auth().currentUser.UID;
//const userEmail = firebase.auth().currentUser.email;
const userID = '1234567890';
const userEmail = 'example@example.com';
//Get email, either personal or work
console.log('Taking a snapshot...');
const snapshot = db.collection('organisations/{orgID}/people').get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.data());
});
});
}
出于测试目的,我注释掉了一些基于身份验证的行。 我知道代码仍然可以运行,因为对orgID进行硬编码确实会返回正确的值。 此外,循环通过每一个组织是不是一个选项,因为我需要有很多组织的可能性。
很多解决方案都是基于firestore触发器的,比如onWrite,您可以使用像这样的通配符。 但是,我认为这在这种情况下是不可能的
有没有人知道这个问题的解决方案,或者可以将我重定向到这样做的源?
当用户登录到您的前端应用程序时,不可能触发云功能。 在Firebase身份验证触发器中没有这样的触发器。
如果您想根据用户的某些特征(uid或电子邮件)更新文档,您可以在用户登录后从应用程序中进行更新。
您在问题中提到,“在这里,需要根据已知的电子邮件地址找到特定的文档”。 您应该首先构建一个查询来查找这个文档,然后更新它,所有这些都是从应用程序中完成的。
另一种经典方法是为每个用户创建一个使用用户uid作为文档ID的特定文档,例如在users
集合中。 这样就很容易识别/找到这个文档,因为用户一登录就知道他的UID。
首先根据官方文档设置云功能。
然后像这样设置create函数之后:
exports.YOURFUNCTIONNAME= functions.firestore
.document('organisations/[randomly generated id]/people/[randomly generated id]')
.oncreate(res => {
const data = res.data();
const email = data.email;/----Your field name goes here-----/
/-----------------Then apply your logic here---------/
)}
这将在您创建People->时触发该函数; 随机ID
我不确定我是否正确理解您的意思,但是如果您想要在所有人
集合中搜索,而不管它们在什么组织
文档下,解决方案是对此使用集合组查询。
db.collectionGroup('people').get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log("user: "+doc.id+" in organization: "+doc.ref.parent.parent.id);
});
});
这将返回整个Firestore数据库中所有people
集合的快照。