我正在嘗試獲取 firestore 中特定用戶的設備令牌,該令牌存盤在“客戶”或“律師”集合內的令牌集合中。當我從鏈中洗掉第二個.collection("tokens")時,我取回了用戶物件,但使用鏈中的令牌集合,我似乎無法取回任何用戶(客戶或律師),即使用戶它的令牌存在。我究竟做錯了什么
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") {
}
})
uj5u.com熱心網友回復:
這條線
if (!snapshot.exists) {
應該:
if (snapshot.empty) {
因為您正在呼叫get()a CollectionReference(回傳 a QuerySnapshot),而不是呼叫a DocumentReference(回傳 a DocumentSnapshot)。
如果您.collection('tokens')從示例中的鏈中洗掉,它確實有效,因為 aDocumentSnapshot確實有成員exists,但 aCollectionReference沒有。
在這里看看他們的成員:
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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/379293.html
標籤:节点.js 火力基地 谷歌云firestore 谷歌云功能
下一篇:比迭代更有效的動態sql查詢方式
