简体   繁体   English

无法检查嵌套集合中是否存在某个字段 Firebase v9

[英]Unable to check whether a field exists in a nested collection Firebase v9

Sorry I'm still new to this, but I'm trying to check whether a specific field (docName) value already exists in a nested collection to perform as a condition.抱歉,我对此还是个新手,但我正在尝试检查嵌套集合中是否已存在特定字段 (docName) 值以作为条件执行。 I'm new to v9 and I'm slowly working my way around it, but I've looked all over and I'm still unable to get the appropriate solution.我是 v9 的新手,我正在慢慢地解决它,但我已经查看了所有内容,但仍然无法获得合适的解决方案。

Ref:参考:

'teachers/${uid}/contracts/autoDocID'

What I have tried我试过的

const Contract = async (data) => {
    const q = query(collection(db, "teachers", data.uid, "contracts"), where("docName", "==", `${data.docName}`)); 
    const condition = await getDocs(q).exists;

    if(!condition){
        //adding new doc
    }
}

The await getDocs(q) returns a QuerySnapshot object , which doesn't have an exists property. await getDocs(q)返回一个QuerySnapshot object ,它没有exists属性。

Are you looking to check if the snapshot is empty ?您是否要检查快照是否为空

I was able to do it like this:我能够这样做:

const Contracts => async(data) = {
    const docRef = doc(db, "teachers", data.uid);
    const colRef = collection(docRef, "contracts");
    const q = query(collection(db, "teachers", data.uid, "contracts"), where("docName", "==", `${data.docName}`));
    const check = await getDocs(q);

    if(!check){
        await addDoc(colRef, {
            expiration: data.expiration,
            docName: data.docName,
            docUrl: data.docUrl,
        });
    } else {
        console.log('already exists')
    }
}

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

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