szokodiakos / typegoose

Typegoose - Define Mongoose models using TypeScript classes.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] Is it possible to map fieldName to field_name?

DawTaylor opened this issue · comments

We're migrating a project from JS to TS and we decided to go with Typegoose.

Our models use snake_case convention for field names, however it seems that Typegoose does not support it out of the box, at least I couldn't figure out how. Is that possible?

I thought of something like this class;

class UserAddress extends Typegoose {
  @prop({ fieldName: 'zip_code' })
  zipCode: string
}

That would have the following Schema output;

new Schema({
  zip_code: String,
})

i dont know what you are trying to archive, but when you just mean simple usage, @prop() is enough for a string, when you try to reference another model from a different collection, use Ref<T>, if you try to use something like this, translate this to typegoose, documentation is missing for this (i added this, but cant fully understand this), if you mean to give the variable an alias, that is not possible, except you do a get & set virtual function for it

if these above are not what you want, please clarify your question and yes, typegoose uses PascalCase

I'm not trying to reference another model, and I'm not sure how would virtuals or alias help us. We don't actually need a field_name alias, we need to persist the document with field_name while using fieldName on the application.

For instance, a document for the user collection would look like;

{
  avatar_url: 'https://...',
}

We don't actually need a field_name alias, we need to persist the document with field_name while using fieldName on the application.

thats what i meant, when you use some different "alias" in the application / DB, you should define what is saved on your DB and make an alias (virtual) for your application

like:

class Dummy extends Typegoose {
    @prop()
    public save_as_this?: string; // what is saved to the DB

    @prop()
    public get saveAsThis() { // an virtual "alias"
        return this.save_as_this;
    }
    public set saveAsThis(to: string) {
        this.save_as_this = to;
    }
}

but as a note: save_as_this is still visible and usable, and is not recommended, because the virtual just adds overhead....

Thanks for the example @hasezoey.