Relationship for array with objects

Given this example, how would I model a relationship for damageCode? I’m getting Error validating rule relationships: cannot define relationship for property “damages.damageCode” which does not exist in schema for collection.

Document:
{
   "_id":"TEST",
   "_partition":"TEST",
   "damages":[
      {
         "damageCode":"PIRX",
         "shortText":"A comment"
      }
   ],
   "causes":[
      "QZPT"
   ]
}
Relationship:
{
  "causes": {
    "foreign_key": "_id",
    "ref": "#/relationship/mongodb-atlas/realm-test/CauseCodes",
    "is_list": true
  },
  "damages.damageCode": {        <!-------- Not valid!
    "foreign_key": "_id",
    "ref": "#/relationship/mongodb-atlas/realm-test/DamageCodes",
    "is_list": true
  }
}

Any hints?

// Mikael

Can you more clearly describe what this relationship is? In Document, the damageCode property is set to a String "PIRX" which would not be a relationship. Do you want that to be one of the values from a List of DamageCodes?

Perhaps including code for the Models and the code showing what you’re attempting to do, it would clarify the question the question

Sure thing @Jay. Nothing spectacular, the CauseCodes and DamageCodes collections are typical value helps with a few additional fields.

CauseCodes collection document example:
{
   "_id":"QZPT",
   "_partition":"TEST",
   "title": "QZPT",
   "description": "Description of code QZPT"
}

DamageCodes collection document example:
{
   "_id":"PIRX",
   "_partition":"TEST",
   "title": "PIRX",
   "description": "Description of code PIRX"
}

In this example, the relationship to Cause Code is fine but I haven’t found a way to link to Damage Code.

In the business scenario, the user shall select Damage Codes from a list and add an additional comment for each of it. But the same relationship problem comes in other situations as well. Let’s say a collection of order items that references a product collection.

Hi @Mikael_Gurenius

In order to define a relationship on a list of embedded objects you have to define it as such:

 "damages.[].damageCode": {     
    "foreign_key": "_id",
    "ref": "#/relationship/mongodb-atlas/realm-test/DamageCodes",
  }

We actually recently highlighted this to the documentation team and it should be getting added soon hopefully as it is definitely not the easiest thing to realize.

One other option for these sorts of things is to use “Development Mode” to populate your schema. That would have automatically handled this schema generation for you

2 Likes

Thank you! This is exactly what I needed.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.