1
votes

In Firebase Cloud Firestore Security Rules Reference, we see that we can get a document using get() function:

get() takes a path and returns the resource at that path.

Is there any way to check if a value already exist in a document of a collection (like mapping documents to check their values)?

I need to check if there is already a document with the field token identical to the value I want to set. I have tried this, but data is documented to be to a document, not a collection of documents:

service cloud.firestore {
  match /databases/{database}/documents {

    match /deviceTokens/{tokenId} {
      allow read, write: if get(/databases/$(database)/deviceTokens).data.token != request.data.token;
    }
  }
}
1
I'm not sure I understand why you need a collection of documents here, rather than a single document.Doug Stevenson
@DougStevenson I need to check if there is already a document with the field token identical to the value I want to setalessionossa
Sorry if I have made some mistakes with the language, I am Italianalessionossa
Is the {tokenId} different from what you set in data.token?Juan Lara
@JRLtechwriting tokenId references to current document, I need to check all documents in the collection.alessionossa

1 Answers

0
votes

You can make the check outside of security rules. To check if a value exists on a document in a collection:

firebase.firestore().collection('deviceTokens').where("token", "==", newToken).get()
.then(snapshot => {
  if(snapshot.docs.length > 0){
    console.log("token taken");
  } else {
    console.log("token available")
  }
})