0

我想为 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

4

1 回答 1

1

简单而懒惰的解决方法是saveCountry(country: Paritial<CountryClass>)

更复杂的方法(但正确的方法)是从键中过滤掉所有只读属性(getter)和函数并将其用作POJO

-> typegoose 的PR 241目前以这种方式工作

于 2020-05-01T15:18:40.360 回答