Search code examples
javascriptnode.jsmongodbtypescripttypegoose

Array of numbers vs Object type in Typegoose


I'm fairly new to Typegoose. I have created a class with a field that should have an array of numbers such as:

class A {
  ... some other properties ...

  @prop({ required: true })
  public nums!: number[];
}

Following is the sample code to populate a new object:

let field = {};
field.nums= {1,2,3};
a = new A(field);

The problem I'm facing is that whenever I create a new object of the class, instead of saving {1,2,3} in the nums field, the program is saving it as {{1},{2},{3}}. However, when I change the type of nums from number[] to Object, the values are stored as desired.

P.S. I also tried changing type of nums from number[] to Array and still faced the same issue.


Solution

  • I have solved the problem thanks to an issue posted on typegoose github repo. According to the post, while working with property of array types, another property is required in @prop decorator that identifies the type of objects in an array. Following is the updated sample code:

    class A {
      ... some other properties ...
    
      @prop({ required: true, type: [Number] })
      public nums!: number[];
    }