简体   繁体   中英

Firestore check if a key exists, then check if a specific field in the same collection exists

My Firebase firestore is build like this:

duell -> documentID -> key:"l23dsk2ls",(player:uid), ...

Screenshot of the firestore structure

I check if the key is existing like this:

   const db = firebase.firestore();
    var duettsRef = db.collection("duetts");
    export const keyExists = (setKey)=>{
    duettsRef
      .doc('key')
      .get().then(
        doc => {
          if (doc.exists) {
            this.db.collection('duett').doc('key').collection(setkey).get().
               then(sub => {
                  sub.docs.length > 0
          });
        }
      })
    }

If existing, the key is unique. Now, instead of the code above where I only check if the key is existing, I want to know, if the key is existing -> if yes -> if theres is a player:"..." field in the collection, where i found the key. How can I do this?

To check if a value exists, you can use a query , and it would look something like this:

duettsRef
  .where('player', '==', key)
  .get().then(
    snapshot => {
      if (!snapshot.empty) {

You can try running the following code:

const db = admin.firestore();
var duettsRef = db.collection("duetts");
export const keyExists = (setKey) => {
    duettsRef.where("player", "==", playerKey).get().then(querySnapshot => {
        if (!querySnapshot.empty) {
            this.db.collection('duett')
              .doc(playerKey).collection(setkey).get().then(subSnapshot => {
                  console.log(subSnapshot.size);
              });
            }
        })
    }

If you could share screenshot of your Firestore structure then I would be able to update the code as per your use case. But the code above check if any document containing playerKey exists, it check for the same ket in the duett collection.

You can actually use an inequality for tests like this - check if the field is GREATER THAN "\0000" (a unicode null) - documents where the field does NOT exist will NOT be included; all documents that have ANY value (other than literally a single null character) will be returned. Could have a LOT of results, though, so you'll likely also want to use a .limit() if you only want to know IF documents exist, not actually incur the cost of reading them all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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