【发布时间】:2020-08-15 23:16:37
【问题描述】:
我想为 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: '{ name: string; 类型的参数代码:字符串;标志:字符串; }' 不能分配给 '...ing 类型的参数; }' 缺少 'Country' 类型的以下属性:getModelForClass, setModelForClass, buildSchema
【问题讨论】:
标签: typescript typegoose