我正在尝试更新PITA非规范化数据库结构。我知道已经有关于如何检查文档是否存在的答案甚至文档都非常清楚,但我无法找到任何可以检查文档是否存在于更新“set”和“where”的内容。
首先,我想在更新之前检查一个文档是否存在
const staffRef = db.collection("staff").doc(uid)
return staffRef.set({
employeeProfile: employeeProfile
}, {
merge: true
})...
有没有办法检查该文档是否存在于集合中,或者我应该先阅读它以查明该文档是否存在
const staffRef = db.collection("staff").doc(uid)
return staffRef.get()
.then((doc) => {
if (doc.exists) {
return staffRef.set({
employeeProfile: employeeProfile
}, {...
其次我想检查多个文件在哪里
const staffRef = db.collection("staff").where("employerId", "==", uid)
const batch = db.batch()
return staffRef.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
batch.update(doc.ref, { employerProfile: employerProfile })
})...
如果存在,我应该在forEach之后阅读每个doc吗?
第一个答案:是的,对于单个文档,您必须首先使用get()
方法来确定该文档是否存在。
对于指向不存在的文档的
DocumentSnapshot
,任何数据访问都将返回“undefined”。您可以使用exists
属性显式验证文档的存在。
第二个答案:不,如果是Query
的结果,你不需要检查每个文件:你通过循环使用doc
获得的每个querySnapshot.forEach()
确实存在。
QuerySnapshot
包含零个或多个表示查询结果的DocumentSnapshot
对象。