francescov1 / mongoose-tsgen

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

"default" ignored #127

Closed adrianwiechec-at-optilyz closed 12 months ago

adrianwiechec-at-optilyz commented 12 months ago

The default field in schema spec seems to be ignored. For example, for the following user model:

import { Schema, model } from "mongoose";

const UserSchema = new Schema({
  firstName: {
    type: String,
    default: "George",
  },
});

export const User = model("User", UserSchema);

after running npx mtgen user.js, I get:

export type User = {
  firstName?: string;
  _id: mongoose.Types.ObjectId;
};

with firstName as optional field, while clearly it will never actually be undefined, so I'm expecting just:

export type User = {
  firstName: string;
  _id: mongoose.Types.ObjectId;
};
francescov1 commented 12 months ago

Hi @adrianwiechec-at-optilyz, thanks for pointing this out.

I'll look at fixing this ASAP. As a workaround, you can provide required: true.

francescov1 commented 12 months ago

@adrianwiechec-at-optilyz after reviewing, the current behaviour is actually correct.

If you do not specify required: true on a field, it is not a required parameter, even if it has a default value. In this case, it is an optional field which gets initialized to a default value, but can be unset at a later point in time.

Closing this for now, let me know if you have any other questions.

adrianwiechec-at-optilyz commented 11 months ago

That's a bummer (on Mongoose side), but thanks for looking into this! :bow: