typescriptdynamoose

Dynamoose Nested Map/Array in TypeScript Schema


I'm trying to create a schema for the following example:

{
    "foods": [
        {
            "fruits": [{
                "apple": {
                    "color": "red",
                    "shape": "round"
                }
            }]
        }
    ]
}

I was initially trying to do the below structure, which is technically correct and should work but fails due to the bug found in https://github.com/dynamoose/dynamoose/issues/909.

export const FoodsSchema = new dynamoose.Schema({
  foods: {
    type: Array,
    schema: [{
      type: Object,
      schema: {
        fruits: {
          type: Array,
          schema: [{
            apple: {
            type: Object,
              schema: {
                color: String,
                shape: String,
              },
            },
          ],
        },
      },
    }],
  },
});

However it does not seem to work. Was getting TypeError: Cannot read property 'toLowerCase' of undefined. The lowerCase error occurs because of the nested arrays or objects.

I also saw TypeMismatch: Expected foods.0.fruits to be of type object, instead found type object. The latter occurred when I tried to change the schema thinking that may be it, but it was not the problem.


Solution

  • Solution: Extract the nested schema into it's own schema and reference that in the original one.

    const appleSchema = new dynamoose.Schema({
      apple: {
        type: Object,
        schema: {
          color: String,
          shape: String,
        },
      },
    });
    

    and then in the original one:

            fruits: {
              type: Array,
              schema: [appleSchema],
            },