0
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{usersID} {
    allow read;
    allow write: if request.auth.uid != null;
        match /desksCollection/{desksCollectionID} {
        allow read;
        allow write: if resource.data.DeskName != request.resource.data.DeskName;
      }
    }
  }
}

I want to write a rule that will don't allow add same document second time. What is incorrect here ?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • could you provide the error? – PV8 Jul 03 '19 at 08:01
  • Please edit the question to show the code that should be limited by the rule. Rules are meaningless without some code that goes along with them. It also might be the case that your code is simply incorrect. Please be specific about the conditions under which you want to reject a write. Right now your rules just reject a write of a document where the DeskName field is being changed. – Doug Stevenson Jul 03 '19 at 08:01
  • Doug Stevenson thank you for response. In my 'desksCollection' collection i have a docs with field DeskName, I simply want to check if someone want to add the doc with same value at DeskName field reject that post – Sooro Gorgoyan Jul 05 '19 at 07:53

2 Answers2

0

What you are trying to do is not possible with security rules. This would require that you be able to perform a query on desksCollection for documents that match the criteria of having a field with a certain value. However, performing queries is not possible in security rules. You can fetch a document by its ID, but that won't help you here, because you don't know which document to fetch.

If you require that deskName be unique, then consider using that value as the ID of the document. Then you can write a rule to prevent updates if the document already exists.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

Here's how I avoid duplication for tokens You can do it for any field.

First query through document and if null then add that collection.

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    firebaseMessaging.getToken().then((token){
      print(token);
      bool isAvailabe;
      Firestore.instance.collection("tokens").where("token",isEqualTo: token).getDocuments().then((snap){
        if(snap == null){
          Firestore.instance.collection('tokens').add({"token":token}).catchError((error){
            print(error);
          }).catchError((e){
            print(e);
          });
        }
      });

    });

  }
Dragonthoughts
  • 2,180
  • 8
  • 25
  • 28
Sonu Dhakal
  • 31
  • 1
  • 2