简体   繁体   English

如何检查SET和WHERE上是否存在文档

[英]How to check if document exist on SET and WHERE

I'm trying to update PITA denormalised db structure. 我正在尝试更新PITA非规范化数据库结构。 I know there are already answers on how to check if document exist on get even documentation is pretty clear about it but I just cannot find anything what would check if document exist on update "set" and "where". 我知道已经有关于如何检查文档是否存在的答案甚至文档都非常清楚,但我无法找到任何可以检查文档是否存在于更新“set”和“where”的内容。

First I want to check one document if exist before updating 首先,我想在更新之前检查一个文档是否存在

 const staffRef = db.collection("staff").doc(uid)

    return staffRef.set({
        employeeProfile: employeeProfile
    }, {
            merge: true
        })...

Is there any way to check if that document exist on set or should I first read it to find out if that document exist like this 有没有办法检查该文档是否存在于集合中,或者我应该先阅读它以查明该文档是否存在

    const staffRef = db.collection("staff").doc(uid)
    return staffRef.get()
        .then((doc) => {
            if (doc.exists) {
                return staffRef.set({
                    employeeProfile: employeeProfile
                }, {...

Second I want to check multiple documents on where 其次我想检查多个文件在哪里

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 })
            })...

Should I read the each doc after forEach if exist? 如果存在,我应该在forEach之后阅读每个doc吗?

First answer: Yes, for a single document, you have to first use the get() method to find out if that document exists. 第一个答案:是的,对于单个文档,您必须首先使用get()方法来确定该文档是否存在。

For a DocumentSnapshot that points to a non-existing document, any data access will return 'undefined'. 对于DocumentSnapshot指向一个不存在的文件,任何数据访问将返回“未定义”。 You can use the exists property to explicitly verify a document's existence. 您可以使用exists属性显式验证文档的存在。

Second answer: No, in case of the results of a Query , you don't need to check each document: each doc you get by looping with querySnapshot.forEach() does exist. 第二个答案:不,如果是Query结果,您不需要检查每个文档:通过使用querySnapshot.forEach()循环获得的每个doc都存在。

A QuerySnapshot contains zero or more DocumentSnapshot objects representing the results of a query. QuerySnapshot包含零个或多个表示查询结果的DocumentSnapshot对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM