我正在尝试从 onCreate 内的 cloud firestore 中的用户集合中检索设备令牌。d.get("token")
; 下面返回一个未定义的。
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
const fcm = admin.messaging();
exports.senddevices = functions.firestore
.document("notification/{id}")
.onCreate((snap, context) => {
const name = snap.get("name");
const subject = snap.get("subject");
return admin.firestore()
.doc("users/{id}")
.get()
.then((d) => {
if (!d.empty) {
const payload = {
notification: {
title: "from " + name,
body: "subject " + subject,
sound: "default",
},
};
d.
const token = d.get("token");
return fcm.sendToDevice(token, payload);
} else {
console.log("User not found");
}
});
});
您需要从.document()
方法中提供的路径中读取 ID 的值,然后在.doc()
方法中使用它来获取文档,如下所示:
exports.senddevices = functions.firestore
.document("notification/{id}")
.onCreate((snap, context) => {
const name = snap.get("name");
const subject = snap.get("subject");
const id = context.params.id
// ^^ reading value of ID
return admin.firestore()
.doc("users/"+id) // <-- Using ID,
//or .doc(`users/${id}`)
.get()
.then((d) => {
if (d.exists) {
const payload = {
notification: {
title: "from " + name,
body: "subject " + subject,
sound: "default",
},
};
const token = d.data().token;
return fcm.sendToDevice(token, payload);
} else {
console.log("User not found");
}
});
});
请注意您正在获取单个文档,因此您应该使用它d.exists
来检查文档是否存在,而不是.empty
在 QuerySnapshot 上使用。同样要读取令牌字段的值,您应该首先使用.data()
方法将该文档的内容作为对象获取。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句