TypeError: result[0].data 不是函数



>我有一个函数,当有人添加评论时应该发送通知。 但是此错误显示在日志中。

TypeError: result[0].data is not a function
at Promise.all.then.result (/srv/lib/index.js:19:35)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)

这是我的功能。这里面有什么问题?如何改变这一点?

/*eslint-disable */
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.apptTrigger = functions.firestore.document("Comments/{anydocument}").onCreate((snap, context) =>  {
const receiver = snap.data().idUserImage;
const messageis = snap.data().comment;

const toUser = admin.firestore().collection("token").where('idUser', '==', receiver).get();

return Promise.all([toUser]).then(result => {
const tokenId = result[0].data().token;
const notificationContent = {
notification: {
title: "Dodano komentarz",
body: messageis,
icon: "default",
sound : "default"
}};
return admin.messaging().sendToDevice(
tokenId,
notificationContent
).then(results => {
console.log("Notification sent!");
//admin.firestore().collection("notifications").doc(userEmail).collection("userNotifications").doc(notificationId).delete();
});
});
});

这是正常的,因为Queryget()方法返回的承诺返回一个QuerySnapshot"包含零个或多个表示查询结果的 DocumentSnapshot 对象"。因此,没有data()方法可用于result[0]

QuerySnapshot文档(上面的链接)说:

可以通过docs 属性或 docs作为数组访问文档 使用 forEach 方法枚举。文档数量可以是 通过空和大小属性确定。

因此,您应该使用docs属性,该属性返回"QuerySnapshot中所有文档的数组",并执行以下操作:

const tokenId = result[0].docs[0].data().token;

但请注意,您不需要在Promise.all的情况下使用,因为您向它传递的是一个只有一个元素的数组。您只需要使用get()返回的QuerySnapshot,并使用其docs属性,如下所示:

exports.apptTrigger = functions.firestore
.document('Comments/{anydocument}')
.onCreate((snap, context) => {
const receiver = snap.data().idUserImage;
const messageis = snap.data().comment;
const toUser = admin
.firestore()
.collection('token')
.where('idUser', '==', receiver)
.get();
return toUser
.then(querySnapshot => {
const tokenId = querySnapshot.docs[0].data().token;
const notificationContent = {
notification: {
title: 'Dodano komentarz',
body: messageis,
icon: 'default',
sound: 'default'
}
};
return admin.messaging().sendToDevice(tokenId, notificationContent);
})
.then(results => {   //If you don't need the following console.log() just remove this then() 
console.log('Notification sent!');
return null;
});
});

错误指出"result[0].data"不起作用。但是,您正在从 result[0] 对象访问"数据"作为函数。

const tokenId = result[0].data().token;

您可能需要将上面的代码行更改为

const tokenId = result[0].data.token;

但在此之前,我建议检查"数据"本身是否被定义。

const tokenId;
if(result[0].data)
tokenId = result[0].data.token;

最新更新