我目前正尝试在Flutter应用程序中使用Firebase Cloud函数。在我的应用程序中,当使用typescript发生事件时,我想从某个文档中检索文档字段。我以前在dart中也做过同样的事情,但我不确定在使用typescript时该怎么做。在下面的代码中,我试图使用dart中的方法从文档中获取字段,但它在typescript中失败,并出现以下错误:
Property 'snapshot' does not exist on type 'DocumentReference<DocumentData>'. Did you mean 'onSnapshot'?
我已经将代码简化为一个云函数,其中最重要的部分前面有注释。我正在尝试从personFromdocumentReference中获取昵称字段。
const db = admin.firestore();
const fcm = admin.messaging();
export const sendToDevice = functions.firestore
.document('messages/{groupChatId}/{chatId}/{message}')
.onCreate(async (snapshot: { data: () => any; }) => {
const message = snapshot.data();
if (message != null) {
const querySnapshot = await db
.collection('messages')
.doc(message.idTo)
.collection('tokens')
.get();
// **** This is where I am referencing the document where I want to get its fields ****
var personFrom = db.collection('messages').doc(message.idFrom).snapshot();
const tokens = querySnapshot.docs.map((snap: { id: any; }) => snap.id);
const payload: admin.messaging.MessagingPayload = {
notification: {
// **** Right here in the title parameter is where I am attempting to retrieve a specific field of data from the document I mentioned above ****
title: "New Message from" + personFrom["nickname"]+ "!",
body: message.content,
icon: 'your-icon-url',
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
};
return fcm.sendToDevice(tokens, payload);
} else {
return undefined
}
});
在JavaScript中,您可以对DocumentReference使用get((来获取文档。它返回一个用DocumentSnapshot对象解析的promise:
const personFrom = await db.collection('messages').doc(message.idFrom).get();
const data = personFrom.data();
现在,data有一个描述文档内容的JavaScript对象。