【问题标题】:Use a TypeScript type in a schema type in mongoose在 mongoose 的模式类型中使用 TypeScript 类型
【发布时间】: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'
  }
)
...

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

【问题讨论】:

    标签: node.js typescript mongoose mongoose-schema


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2019-01-13
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 2021-03-19
      • 2019-02-03
      • 1970-01-01
      相关资源
      最近更新 更多