I am currently exploring how to create an abstraction for Mongo model functions and looking into ways to reuse the model interface from a typegoose class.
My goal is to have a function like this:
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 to save country', country)
throw err
}
}
Here is the definition of 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
However, when I tried to pass an object
{ name : 'country name', code: 'code', flag: 'flag' }
to the saveCountry
function, I encountered an 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