我想为 Mongo 模型函数创建一个抽象。并搜索如何从 typegoose 类中重用模型接口。
我想要一个像这样的功能:
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
}
}
国家型号:
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
但是当尝试将对象传递{ name : 'country name', code: 'code', fag: 'flag' }
给saveCountry
函数时出现错误:
2345:类型参数'{名称:字符串;代码:字符串;标志:字符串;}' 不能分配给 '...ing; 类型的参数;}' 缺少“国家/地区”类型的以下属性:getModelForClass、setModelForClass、buildSchema