typescripttypegoose

Typegoose - pass arbitrary JSON objects to array


I have a Typegoose model (simplified)

export class SurveyClass extends BaseClass {
  @prop({ required: true, default: '' })
  public description!: string;

  @prop({ required: true, default: [] })
  public questions!: Array<any>;
}

The "questions" array is intended to receive chunks of JSON, for example:

{
  id: "1869050556234435",
  type: "feedback",
  data: "the feedback data"
  i18n: {
    fr: {
      data: "le feedback data"
    }
  }
}

...because the kind and number of these chunks are arbitrary, and many are more deeply nested, I've tried to use Array<any>

This works, but if I pass in data like this:

{
  id: "1869050556234435",
  type: "feedback",
  data: "the feedback data"
  i18n: {}
  }
}

... then the "i18n" key and value is never set in the database. Those fields are "ignored" (though the others are saved.)

I have a few questions associated with this:

  1. Could this be a bug with Typegoose? (ie: should this work?)
  2. If I'm "doing this wrong", is somehow possible to configure this array field to receive arbitrarily nested objects the way I have described? Or would I need to save it as a string (ie: JSON.stringify) to save truly arbitrary object data?
  3. If this can't be done, and the right approach is to build types to save such nested objects into an array, how should this be done? (Hoping for examples both of the type definition and the use of it in the model.)

Solution

  • By default mongoose removes properties that it considers "empty" before insertion.

    If the default "empty" behavior is not wanted:

    Also the the class in the question is not properly formed and requires option type to be set.

    See Quick-Start-Guide Caution Note:

    type has to be defined when working with Arrays, because Reflection only returns basic information. Look here for why
    Like public: string[] is in reflection only Array.


    Note: i am not sure if the schema option minimize will apply to nested schemas (all nested classes in typegoose are nested Schemas)