Home > Blockchain >  How to query firestore when document does not exist
How to query firestore when document does not exist

Time:06-20

I'm trying to keep a record of user tokens when they subscribe to a topic once.

Im trying to make a query where if a document does not exist with the current user_token, it would create a new document for them, attaching their user_token.

If a document already exist with the same user_token , then it should not run this query and replicate is self, which is my main problem. both document have the same token_id and are duplicated

This is what I tried

//Variables
  let db = Firestore.firestore()
  let user_token = "dpc3GPfPzUArj...IdEac5hWYWI8"

//If no document exist with user_token create a new one
db.collection("tokenList").whereField("token_id",isNotEqualTo: user_token).getDocuments() { 
    (querySnapshot, err) in
        if let err = err { print("Error getting documents: \(err)") } 
    else {
    db.collection("tokenList").document().setData(["token_id" : user_token])                                                                      
    }
 
//If one already exist, this query should not run

CodePudding user response:

Invert the logic: Search for the first document where token_id === user_token (you can limit it to 1 result). If there's a result, it exists. If there's not, it doesn't exist.

You could also have the token_id be the actual ID of the document, which makes sense if it's the primary identifier.

  • Related