francescov1 / mongoose-tsgen

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

Error of build when a field ```models``` is used in a schema #128

Closed LeoAutomateSAS closed 9 months ago

LeoAutomateSAS commented 11 months ago

Hello,

it appears that when a field models is used as a standard schema fields, tsgen interpretes it in a wrong way (as a reserved word ?) :

This definition fails :

const LandingPageSchema = new Schema({
    brand: String,
    models: [
        {
            name: String,
            imgUrl: String,
            modelUrl: String,
            metadata: {
                title: String,
                description: String,
                keywords: [String],
            },
        },
    ],
})

with ts-gen outputs : image image

This definition works (after changing the models field):

const LandingPageSchema = new Schema({
    brand: String,
    brandsModels: [
        {
            name: String,
            imgUrl: String,
            modelUrl: String,
            metadata: {
                title: String,
                description: String,
                keywords: [String],
            },
        },
    ],
})

tsgen installed version : 9.2.7

francescov1 commented 11 months ago

Hey @LeoAutomateSAS, yes the conflict is because we name our models {collection name}Model, and subdocument models are named {root model}{field name}. Let me look into this and see if there's an easy fix to check for conflicts and mitigate them.

francescov1 commented 11 months ago

Hi @LeoAutomateSAS, I found a solution. Essentially I can check if a field conflicts with the model name and append a string to it to avoid the conflict.

So in effect, your type would result in something like this:

export type LandingPage = {
  brand?: string;
  models: LandingPageModel{post fix to add}[];
  _id: mongoose.Types.ObjectId;
};

Any thoughts on what youd want the post fix to be? I havent had this use case from anyone else so would love some input. I was thinking Subdoc, but its a bit weird because we would end up generating a LandingPageModelSubdocDocument type. Maybe Field? So it would be named LandingPageModelField and LandingPageModelFieldDocument.

francescov1 commented 9 months ago

Fix is live in v9.2.9!