【问题标题】:How to get typegoose class model interface如何获取typegoose类模型接口
【发布时间】: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


    【解决方案1】:

    简单而懒惰的解决方法是saveCountry(country: Paritial&lt;CountryClass&gt;)

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多