francescov1 / mongoose-tsgen

A plug-n-play Typescript generator for Mongoose.
103 stars 24 forks source link

[bug] Using `type` as a field causes the types to be generate incorrectly #135

Closed wootwoot1234 closed 7 months ago

wootwoot1234 commented 8 months ago

Thanks for the great library, it works great!

I found a bug when using type as a field inside of a type object, which causes the types to be generated incorrectly. Here's an example:

const Account = new Schema(
    {
        ...
        seam: {
            type: {
                accountId: {type: String, required: true},
                type: {type: String, required: true}
            },
            required: false,
            _id: false
        },
        ...
    }
);

will generate:

...
    seam: {
      type: {
        accountId: string;
        type: string;
      };
      required?: any;
    };
...

If we comment out the type definition, it works as expected:

const Account = new Schema(
    {
        ...
        seam: {
            type: {
                accountId: {type: String, required: true}
                // type: {type: String, required: true}
            },
            required: false,
            _id: false
        },
        ...
    }
);
...
    seam?: AccountSeamDocument;
...
francescov1 commented 8 months ago

Hmm yeah with the various levels of type, its hard to differentiate between a field named type and the type of a higher level field. Looking through the code, there isn't any great ways to resolve this.

I think the best solution would be to define a separate schema here, something like the following:

const Seam = new Schema({
     accountId: {type: String, required: true},
     type: {type: String, required: true}
   }, 
   { _id: false }
)

const Account = new Schema(
    {
        seam: {
            type: Seam.schema,
            required: false
        }
    }
);

It also makes the schema definitions a bit more clear to a reader. Would this work for you?

wootwoot1234 commented 7 months ago

This worked great, thank you!