francescov1 / mongoose-tsgen

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

Support ref functions #145

Closed richard-jfc closed 3 months ago

richard-jfc commented 4 months ago

I'm seeing the error:

TypeError: val.ref.replace is not a function

When trying to generate with a schema that uses a function for its ref:

import { Schema, model } from 'mongoose';
import type { TestDocument, TestModel } from '../interfaces/models.gen';

const TestSchema = new Schema({
  foodType: {
    type: String,
    required: true,
    enum: ['main', 'desert'],
  },
  food: {
    type: Schema.Types.ObjectId,
    ref: function (this: TestDocument) { // This is fine if ref is a constant, but not if it's a function
      if (this.foodType === 'main') {
        return 'Main';
      } else {
        return 'Desert';
      }
    },
  },
});

export const Test = model<TestDocument, TestModel>('Test', TestSchema);

It would be great if it could determine (from the typescript types) that the type should be: MainDocument['_id'] | MainDocument | DesertDocument['id'] | DesertDocument

I guess a slightly easier fix might be to just return mongoose.Types.ObjectId

francescov1 commented 3 months ago

Hey @richard-jfc,

Doing the full fix you suggest is quite a bit tougher. We'd need to support reading the Typescript AST within a schema (currently the typescript AST reading is only done for methods, statics, virtuals and other surrounding items, but parsing the fields themselves will be a bit more complicated. Would be great to add this eventually but don't have the time right now.

For the time being I made the simpler fix you suggested, live in v9.3.2. Feel free to re-open this if you don't think its satisfactory, and will try to get to it when things open up