检查 Firestore 文档是否存在和 return 布尔值
Check if Firestore document exists and return boolean
我想制作一个 returns true
或 false
的实用函数,具体取决于集合中是否存在 firestore 文档。
下面是我最初写的,但它 return 是一个承诺而不是布尔值。
async function docExists(docName, docId) {
const docRef = db.collection(docName).doc(docId);
await docRef.get().then((docSnapshot) => {
if (docSnapshot.exists) {
return true
} else {
return false
}
});
}
有没有办法让它 return 一个布尔值,或者这只是解决问题的错误方法?
没有必要像您在问题中那样混合使用 await
和 .then
语法。这应该足够了:
async function docExists(docName, docId) {
const docRef = db.collection(docName).doc(docId);
let docSnapshot = await docRef.get();
if (docSnapshot.exists) {
return true;
} else {
return false;
}
}
或者,通过使用 promise chaining,您应该能够简单地在问题中的原始 await docRef.get().then(...)
之前添加 return
关键字。
一个简单的衬垫可以是:
const docExists = async (docName, docId) => (await db.collection(docName).doc(docId).get()).exists
我想制作一个 returns true
或 false
的实用函数,具体取决于集合中是否存在 firestore 文档。
下面是我最初写的,但它 return 是一个承诺而不是布尔值。
async function docExists(docName, docId) {
const docRef = db.collection(docName).doc(docId);
await docRef.get().then((docSnapshot) => {
if (docSnapshot.exists) {
return true
} else {
return false
}
});
}
有没有办法让它 return 一个布尔值,或者这只是解决问题的错误方法?
没有必要像您在问题中那样混合使用 await
和 .then
语法。这应该足够了:
async function docExists(docName, docId) {
const docRef = db.collection(docName).doc(docId);
let docSnapshot = await docRef.get();
if (docSnapshot.exists) {
return true;
} else {
return false;
}
}
或者,通过使用 promise chaining,您应该能够简单地在问题中的原始 await docRef.get().then(...)
之前添加 return
关键字。
一个简单的衬垫可以是:
const docExists = async (docName, docId) => (await db.collection(docName).doc(docId).get()).exists