How to insert a document in MongoDB stitch with rule enabled on a field

1.6k views Asked by At

I am trying the new MongoDb stitch but cannot work out with defining rules on fields.

When I try to insert a document it collection with no rules on any Fields or only in Top level document it inserts fine. But as soon as I add a Field an write a rule it gives error "document cannot be written to". Even when the rule is "{}" which always evaluates to true. Below is a sample insert Pipeline and defined rule.

TOP LEVEL DOCUMENT: R {} W "blank" FIELDS : name W {}

Insert Pipeline Stage 1 :

Service: "built-in", Action "literal", 
args:"{
  "items": [
    {
      "name": "Don Giovanni",
      "cuisine": "Italian",
      "location": "Chicago, IL",
      "comments": [
        {
          "user_id": "leporello",
          "comment": "Molto bene"
        },
        {
          "user_id": "59b256814fdd1f75d5e1dce3",
          "comment": "insertion"
        },
        {
          "user_id": "59b256814fdd1f75d5e1dce3",
          "comment": "good food"
        },
        {
          "user_id": "59b256814fdd1f75d5e1dce3",
          "comment": "very good food"
        },
        {
          "user_id": "59b256814fdd1f75d5e1dce3",
          "comment": "insertion"
        }
      ]
    }
  ]
}"

Stage 2 :
Service :"mongodb-atlas", Action:"insert",database:"guidebook", collection:"restaurants"
1

There are 1 answers

1
AudioBubble On

If your write rule at the top-level document is blank, Stitch will try to find a writeable rule for each of the fields/arrays/sub-documents that would apply to the document you're trying to insert.

In your case, it's not enough to have a write all (i.e. {}) rule for the name field, you need one for each other field present in your document (i.e. _id, location, cuisine and comments), as shown in the picture below. Note that you must declare the comments field as Array not Any for your insert to work.

You can find out more about the Stitch rules interaction in the Stitch documentation: https://docs.mongodb.com/stitch/rules/mongodb-rules/#mongodb-service-rules-interaction

Stitch rules