[英]how to get a document from firestore using a function in typescript?
I wanted to get user information from my collection using their ID to send them notifications.我想从我的收藏中获取用户信息,使用他们的 ID 向他们发送通知。 This are my functions in index.ts
这是我在 index.ts 中的函数
export const sendNotifications = functions.firestore
.document('messages/{groupId1}/{groupId2}/{message}')
.onCreate((snapshot, context) =>{
console.log('Starting sendNotification Function');
const doc = snapshot.data();
console.log(doc.content);
console.log(getUserData(doc.idFrom))
return true;
});
export async function getUserData(id: string){
try {
const snapshot = await admin.firestore().collection('users').doc(id).get();
const userData = snapshot.data();
if(userData){
return userData.nickname;
}
} catch (error) {
console.log('Error getting User Information:', error);
return `NOT FOUND: ${error}`
}
}
From my deploy, I get the console log messages, the 'Starting sendNotification Function', then the actual 'doc.content' then an error for my 'getUserData(doc.idFrom)'.从我的部署中,我收到控制台日志消息,“正在启动 sendNotification 函数”,然后是实际的“doc.content”,然后是“getUserData(doc.idFrom)”的错误。
Promise {
<pending>,
domain:
Domain {
domain: null,
_events: { error: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] } }
Thank you in advance!先感谢您!
You should call your async getUserData()
function with await
.你应该用
await
调用你的 async getUserData()
function 。
The following should do the trick (untested):以下应该可以解决问题(未经测试):
export const sendNotifications = functions.firestore
.document('messages/{groupId1}/{groupId2}/{message}')
.onCreate(async (snapshot, context) => {
try {
console.log('Starting sendNotification Function');
const doc = snapshot.data();
console.log(doc.content);
const nickname = await getUserData(doc.idFrom);
// Do something with the nickname value
return true;
} catch (error) {
// ...
}
});
async function getUserData(id: string) {
try {
const snapshot = await admin.firestore().collection('users').doc(id).get();
if (snapshot.exists) {
const userData = snapshot.data();
return userData.nickname;
} else {
//Throw an error
}
} catch (error) {
// I would suggest you throw an error
console.log('Error getting User Information:', error);
return `NOT FOUND: ${error}`;
}
}
Or, if you don't want to have the Cloud Function async, you can do as follows:或者,如果您不想让 Cloud Function 异步,您可以执行以下操作:
export const sendNotifications = functions.firestore
.document('messages/{groupId1}/{groupId2}/{message}')
.onCreate((snapshot, context) => {
console.log('Starting sendNotification Function');
const doc = snapshot.data();
console.log(doc.content);
return getUserData(doc.idFrom)
.then((nickname) => {
// Do something with the nickname value
return true;
})
.catch((error) => {
console.log(error);
return true;
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.