在 mongoose 的模式类型中使用 TypeScript 类型

Posted

技术标签:

【中文标题】在 mongoose 的模式类型中使用 TypeScript 类型【英文标题】:Use a TypeScript type in a schema type in mongoose 【发布时间】:2021-10-17 01:33:36 【问题描述】:

如何在猫鼬模式中使用 TS 类型?我有以下内容:

...
type Associated = 
  associatedId : string
  imei         : string
  vehicleTypeId: string


interface IGroup extends Document 
  ...
  associated: Associated
  ...


const Group = new Schema(
  
    ...
    associated: 
      type: Associated
    ,
    ...
  ,
  
    collection: 'group'
  
)
...

但我收到一个错误:“关联”仅指一种类型,但在此处用作值。

【问题讨论】:

【参考方案1】:

我自己从未尝试过(尽管我很可能会在此之后尝试),但是通过互联网搜索,我发现基本上有两种选择可以实现类似的事情:

在此链接Mongoose the Typescript way...? 下找到用户 Louay Alakkad 的答案

export interface IUser extends mongoose.Document 
  name: string; 
  somethingElse?: number; 
;

export const UserSchema = new mongoose.Schema(
  name: type:String, required: true,
  somethingElse: Number,
);

const User = mongoose.model<IUser>('User', UserSchema);
export default User;

一个更接近于实现你在 GitHub 上用 1.4k 星描述的库的库,看起来它是在一周前的最后一次提交中维护的 https://github.com/typegoose/typegoose

【讨论】:

以上是关于在 mongoose 的模式类型中使用 TypeScript 类型的主要内容,如果未能解决你的问题,请参考以下文章