francescov1 / mongoose-tsgen

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

Support typescript enums #143

Closed richard-jfc closed 5 months ago

richard-jfc commented 5 months ago

Mongoose supports setting enums from a typescript enum (https://github.com/Automattic/mongoose/issues/9546), but mongoose-tsgen generates a string type.

import { Schema, model } from "mongoose";

enum Status {
  draft = 'draft',
  trash = 'trash',
  published = 'published',
  archive = 'archived',
}

const TestSchema = new Schema({
  status: {
    type: String,
    enum: Status,
    required: true,
  },
});
export const TestModel = model('test', TestSchema);

Actual Output:

export type test = {
  status: string;
  _id: mongoose.Types.ObjectId;
};

Expected Output:

export type test = {
  status: 'draft' | 'trash' | 'published' | 'archived';
  _id: mongoose.Types.ObjectId;
};

Work Around:

const TestSchema = new Schema({
  status: {
    type: String,
    enum: Object.values(Status),
    required: true,
  },
});
richard-jfc commented 5 months ago

It would actually be great if it could do even better and reference the original enum (if it is exported).

Output:

export type test = {
  status: Status;
  _id: mongoose.Types.ObjectId;
};
francescov1 commented 5 months ago

Nice catch, I didn't know mongoose supported passing enums directly. Will take a look this weekend. Handling the parsing of an enum type should be no problem so I'll start there to get you support ASAP, but referencing the original enum will likely be a bit more involved.

francescov1 commented 5 months ago

Fix live in v9.3.0 🚀 I dont think im going to be able to get to your second use case as its much more complicated to integrate, but let me know if its critical and I can try to plan it late in the summer