我想在 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 = '[email protected] /cdn-cgi/l/email-protection';
//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,您可以在其中使用像这样的通配符。
但是,我认为在这种情况下这是不可能的
上述问题的解决办法:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
//Add UID to document in DB[FMIS-94]
//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 = '[email protected] /cdn-cgi/l/email-protection';
var docFound = false;
//Get email, either personal or work
console.log('Taking a snapshot...');
//Test for work email
const snapshot = db.collectionGroup('people').where('email.work', '==', userEmail).get()
.then(function(querySnapshot){
querySnapshot.forEach(function(doc){
//work email found
console.log('work email found');
console.log(doc.data());
docFound = true;
const organisationID = doc.ref.parent.parent.id;
writeUID(doc.id, userID, organisationID);
});
});
if(!docFound){
//Test for personal email
const snapshot = db.collectionGroup('people').where('email.personal', '==', userEmail).get()
.then(function(querySnapshot){
querySnapshot.forEach(function(doc){
//personal email found
console.log('personal email found');
console.log(doc.data());
const organisationID = doc.ref.parent.parent.id;
writeUID(doc.id, userID, organisationID);
});
});
}
}
async function writeUID(doc, uid, organisationID){
const res = db.collection(`organisations/${organisationID}/people`).doc(doc).set({
userId: uid
}, { merge: true });
}
这正是我所需要的,感谢大家的帮助!