[英]Getting ID of a firestore document using a conditional query in Node,js using then()
我一直在嘗試使用條件獲取 firestore 文檔 ID。 比如,如果文檔有其 secret_code 字段“ABCD12”,則獲取該文檔的 ID。 我一直在嘗試使用 Node.js 執行此操作,但它似乎不起作用。 代碼返回 {Promise}
我想我還不夠了解 then() 。
`
async function getIdFromSecretCode(secret_code) {
doc_id=0
await userCollection
.where("secret_code", "==", secret_code)
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
// doc.data() is never undefined for query doc snapshots
doc_id = doc.id;
// console.log(doc_id);
//console.log(doc.id, " => ", doc.data());
});
});
return doc_id;
}
var t= getIdFromSecretCode("ABCD")
console.log(t)
`
o/p 是:`
PS E:\socketio-unity-main> node mserver.js
Promise { <pending> }
` 我希望它返回文檔 ID,如“1xccecefgrf”
getIdFromSecretCode
是一個async
function,因此它總是返回 promise。您不能指望現在可以獲得未來的結果,因此您需要接受承諾,在對getIdFromSecretCode
的主要調用中也是如此。
此外,promise 目前沒有解析任何有用的東西,所以你必須稍微調整一下代碼:
async function getIdFromSecretCode(secret_code) {
const snapshot = await userCollection
.where("secret_code", "==", secret_code)
.get();
return snapshot.docs[0]?.doc_id;
}
getIdFromSecretCode("ABCD").then(t => {
console.log(t);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.