Search code examples
typescripttypegoose

How to get typegoose class model interface


I want to create an abstraction for Mongo model functions. And searching how to reuse model interface from typegoose class.

I want to have a function like:

import CountryModel, { Country } from '../../models/country/CountryModel'

export async function saveCountry(country: Country): Promise<Country> {
  try {
    const res = await new CountryModel(country).save()

    return res.toObject()
  } catch (err) {
    console.log('Failed save country', country)
    throw err
  }
}

CountryModel:

import mongoose from 'mongoose'
import { prop, Typegoose } from 'typegoose'

export class Country extends Typegoose {
  @prop({ required: true })
  name!: string

  @prop()
  code?: string

  @prop()
  flag?: string
}

const CountryModel = new Country().getModelForClass(Country, {
    existingMongoose: mongoose,
    schemaOptions: {collection: 'country'}
})

export default CountryModel

but when try pass object { name : 'country name', code: 'code', fag: 'flag' } to saveCountry function I got error:

2345: Argument of type '{ name: string; code: string; flag: string; }' is not assignable to parameter of type '...ing; }' is missing the following properties from type 'Country': getModelForClass, setModelForClass, buildSchema


Solution

  • the easy & lazy fix would be saveCountry(country: Paritial<CountryClass>)

    the more complicated way (but correct one) would be to filter out all readonly properties (getters) and functions out of the keys and use it as an POJO

    -> PR 241 from typegoose currently works on such an way