francescov1 / mongoose-tsgen

A plug-n-play Typescript generator for Mongoose.
105 stars 25 forks source link

Defaulting Array field causes TypeError: Cannot read property 'type' of undefined #33

Closed kurtcarpenter closed 3 years ago

kurtcarpenter commented 3 years ago

Glad to see this package and its approach of deriving types from the Schema - this is a great way to avoid 1) duplicating types alongside the Schema 2) rewriting existing Schemas in a new format.

Issue

Specifying a default property for an Array field causes a TypeError: Cannot read property 'type' of undefined here: https://github.com/Bounced-Inc/mongoose-tsgen/blob/df3b86a614b8c5576b3ab83213100af5c8910586/src/helpers/parser.ts#L392

This is not occurring with default specified for other types, such as String, Number, and Boolean.

Repro steps

In a repo with valid tsconfig.json and the following filefoo.js, run npx mtgen foo.js.

import { model, Schema } from "mongoose";

export default model("foo", new Schema({
  myArray: {
    type: [{
      a: String
    }],
    default: [] // removing this line causes type generation to work correctly
  }
}));
francescov1 commented 3 years ago

Thanks for pointing this out and the reproducing steps! Mongoose has so many ways to define types I was worried there may be some missing edge cases, I'll publish a fix for this over the weekend 🚀

francescov1 commented 3 years ago

@kurtcarpenter I believe the default: [] is actually unecessary in your case. Since myArray is inferred by Mongoose as a subdocument array, it will be given a default value of [] automatically. See example:

import { model, Schema } from "mongoose";

const A = model("foo", new Schema({
  myArray: {
    type: [{
      a: String
    }]
  }
}));

const a = new A()

// prints "{ _id: 60285a8f3bca30212054f2f8, myArray: [] }"
console.log(a)

export default A;

while looking into this I did find that Mongoose provides a way to actually disable this behaviour by passing default: undefined which has not been handled properly by mongoose-tsgen. Will look to provide that support instead.

Let me know if this works, if so I'll go ahead and close this issue.

francescov1 commented 3 years ago

Support for default: undefined added in 7.0.11, also made a small fix so that the tool doesn't break in the example you provided above. Let me know how it goes 😊.