Creating a TypeScript schema with nested maps and arrays using Dynamoose

I'm currently in the process of developing a schema for a specific example:

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

Initially, I attempted the following structure, which theoretically should work but encounters a bug as identified 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 appears to have some issues. I encountered a

TypeError: Cannot read property 'toLowerCase' of undefined
. This error is likely due to the presence of nested arrays or objects.

In addition, I came across

TypeMismatch: Expected foods.0.fruits to be of type object, instead found type object.
. When attempting to modify the schema in an effort to address this issue, it was not the solution.

  • This was observed in version 2.7.0.

Answer №1

Resolution: Separate the nested schema into a distinct schema and reference it within the initial one.

const bananaSchema = new dynamoose.Schema({
  banana: {
    type: Object,
    schema: {
      size: String,
      type: String,
    },
  },
});

Subsequently, in the original schema:

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

Answer №2

Consider an alternative approach by modifying your schema to the following structure:

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

(Hopefully that is accurate).

In the previous fruits schema part, there was an array followed by apple:

schema: [
  apple: {

I may be mistaken, but that doesn't seem like valid JavaScript syntax.

The main idea is that you can achieve what you want within one schema. Alternatively, you could split it into smaller objects rather than schemas for simplicity.

As mentioned in another response, dividing it into schemas is also a viable option!

There are multiple approaches to solving this issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a Nuxt error where properties of null are being attempted to be read, specifically the 'addEventListener' property. As a result, both the default

Currently, I am utilizing nuxt.js along with vuesax as my UI framework. I made particular adjustments to my default.vue file located in the /layouts directory by incorporating a basic navbar template example from vuesax. Subsequently, I employed @nuxtjs/ ...

Declare that a method alters a value with state

Here's a more streamlined version of my code. Check out my custom hook below: export const useStep = () => { const [step, setStep] = useState<Steps>("sending"); const changeStep = (newStep: Steps) => setStep(newStep); return { ste ...

Divide the enhanced document into sections using TypeScript

In my project, I am working with Material UI and TypeScript. I have noticed that I need to declare the Theme interface and ThemeOptions in the same file for it to work properly. Is there a more efficient way to separate these declarations from the main t ...

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...

Enhance the capabilities of a basic object by incorporating a superclass through the creation of

I'm currently developing a library using Typescript 2.0 that can be utilized from both Typescript and JavaScript. Within the library, there is a class called Component and a function named registerComponent, both written in Typescript. My goal is to ...

Setting the sidebar width for Nebular with two sidebars in the layout: A step-by-step guide

Having two sidebars (identified as left and right) in my page layout, I initially set both sidebars to a width of 400px using the custom theme method with sidebar-width: 400px. However, I now need to change the width of the right sidebar to 700px. Is the ...

Divide a given number of elements within an array of arrays

Presented below is an array: [ { "id": "34285952", "labs": [ { "id": "13399-17", "location": "Gambia", "edge": ["5062-4058-8562-294 ...

Implementing an interface in TypeScript and assigning it a value using generics?

I'm struggling to make sense of a type declaration I came across in the react-router library: export interface RouteComponentProps< Params extends { [K in keyof Params]?: string } = {}, C extends StaticContext = StaticContext, S = H.Lo ...

Typescript: The type 'T' fails to meet the requirement of being an 'object'

Ever since I installed a package along with its @types package, I've been encountering an issue with the following code: https://i.stack.imgur.com/rrRhW.png This is the error message that I'm receiving: https://i.stack.imgur.com/BfNmP.png The ...

Issue with InversifyJS @multiInject: receiving an error stating "ServiceIdentifier has an ambiguous match"

Having an issue with inversifyJs while trying to implement dependency injection in my TypeScript project. Specifically, when using the @multiInject decorator, I keep receiving the error "Ambiguous match found for serviceIdentifier". I've been referenc ...

Searching for a string within a JSON object in Angular: step-by-step guide

JSON Data Example { "rootData": { "test1": { "testData0": "Previous information", "testData1": "Earlier Information" }, "test2": { "testData0": ...

What is the reason behind Typescript not narrowing generic union type components when they are eliminated by type guards?

Consider the following scenario where type definitions and function implementations are provided: interface WithNumber { foo: number; } interface WithString { bar: string; } type MyType = WithNumber | WithString; interface Parameter<C extends My ...

In TypeScript, Firestore withConverter may return a QueryDocumentSnapshot instead of the expected Class object

I'm currently exploring the usage of Firestore's withConverted method in Typescript to retrieve queries as instances of my customized class. Custom EventConverter Class import Event from "@/models/Event"; class EventConverter implemen ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

The necessity of the second parameter, inverseSide property in TypeORM's configurations, even though it is optional

As I delve into learning Typescript and TypeORM with NestJS simultaneously, a recent use-case involving the OneToMany and ManyToOne relation decorators caught my attention. It seems common practice for developers to include the OneToMany property as the se ...

Node.js and Express: The error message "Cors is not a function"

Everything was running smoothly until this morning when out of nowhere, a type error popped up stating that Cors is not a function Here's my code: import * as Cors from "cors"; ... const corsOptions: Cors.CorsOptions = { allowedHeaders: ["Origi ...

Leverage the generic parameter type inferred from one function to dynamically type other functions

I am in the process of developing an API for displaying a schema graph. Here is a simplified version of what it entails: interface Node { name: string; } type NodeNames<T extends Node[]> = T[number]["name"]; // Union of all node names as strings ...

The error message is: "Cannot access property 'up' of an undefined object within the material UI library using theme.breakpoints."

I am encountering difficulties with the export of makeStyles. Below you can find my code and configuration: import SearchField from "../SearchField"; import { TextField, Select, useMediaQuery, Grid, Button, Box, Fade } from '@material-ui/core&ap ...

Suggestions for enhancing or troubleshooting Typescript ts-node compilation speed?

Recently, I made the switch to TypeScript in my codebase. It consists of approximately 100k lines spread across hundreds of files. Prior to the migration, my launch time was an impressive 2 seconds when using ESLint with --fix --cache. However, after impl ...

What could be causing the issue with my customized sorting in the Material-UI Data Grid component?

After integrating Material-UI's Data Grid Component with my API's JSON array, I had to create a RenderCell function to handle text overflow and include a button that directs Users to a different page. Additionally, I utilized the ValueGetter for ...