我正试图在firestore中获取特定用户的设备令牌,该令牌存储在";客户端";或";律师";收集当我从链中移除第二个.collection("tokens"(时,我会取回用户对象,但由于链中有token集合,我似乎无法取回任何用户(客户或律师(,即使用户及其令牌存在。我做错了什么
exports.onReceiveChatMessage = functions.database
.ref("/messages/{uid}")
.onCreate(async (snapshot, context) => {
const newMessage = snapshot.val();
console.log("NEW_MESSAGE", newMessage);
const senderName = newMessage.sender_name;
const messageContent = newMessage.content;
console.log("SENDER'S_NAME", senderName);
console.log("MESSAGE_BODY", messageContent);
const uid = context.params.uid;
console.log("RECEIVERS_ID", uid);
if (newMessage.sender_id == uid) {
//if sender is receiver, don't send notification
console.log("sender is receiver, dont send notification...");
return;
} else if (newMessage.type === "text") {
console.log(
"LETS LOOK FOR THIS USER, STARTING WITH CLIENTS COLLECTION..."
);
let userDeviceToken;
await firestore
.collection("clients")
.doc(uid)
.collection("tokens")
.get()
.then(async (snapshot) => {
if (!snapshot.exists) {
console.log(
"USER NOT FOUND IN CLIENTS COLLECTION, LETS CHECK LAWYERS..."
);
await firestore
.collection("lawyers")
.doc(uid)
.collection("tokens")
.get()
.then((snapshot) => {
if (!snapshot.exists) {
console.log(
"SORRY!!!, USER NOT FOUND IN LAWYERS COLLECTION EITHER"
);
return;
} else {
snapshot.forEach((doc) => {
console.log("LAWYER_USER_TOKEN=>", doc.data());
userDeviceToken = doc.data().token;
});
}
});
} else {
snapshot.forEach((doc) => {
console.log("CLIENT_USER_TOKEN=>", doc.data());
userDeviceToken = doc.data().token;
});
}
});
// console.log("CLIENT_DEVICE_TOKEN", userDeviceToken);
} else if (newMessage.type === "video_session") {
}
})
此行
if (!snapshot.exists) {
应该是:
if (snapshot.empty) {
因为您在CollectionReference
(返回QuerySnapshot
(上调用get()
,而不是在DocumentReference
(返回DocumentSnapshot
(上调用。
如果在您的示例中从链中删除.collection('tokens')
,它确实有效,因为DocumentSnapshot
确实有成员exists
,但CollectionReference
没有。
在这里看看他们的成员:
https://googleapis.dev/nodejs/firestore/latest/CollectionReference.html#get
然后:
https://googleapis.dev/nodejs/firestore/latest/QuerySnapshot.html
作为一个建议,我曾经混淆快照,因为使用Javascript而不是Typescript,所以出现了这个问题。因此,我习惯了在对文档调用时调用结果snap
,在对集合调用时调用snaps
。这让我想起了我正在做的回应。比如:
// single document, returns a DocumentSnapshot
const snap = await db.collection('xyz').doc('123').get();
if (snap.exists) {
snap.data()...
}
// multiple documents, returns a QuerySnapshot
const snaps = await db.collection('xyz').get();
if (!snaps.empty) { // 'if' actually not needed if iterating over docs
snaps.forEach(...);
// or, if you need to await, you can't use the .forEach loop, use a plain for:
for (const snap of snaps.docs) {
await whatever(snap);
}
}