【问题标题】:Mongoose Schema properties validation with Typescript使用 Typescript 验证 Mongoose Schema 属性
【发布时间】:2018-10-09 19:30:37
【问题描述】:

我正在学习 TypeScript 并与猫鼬玩耍。我有以下 Schema 定义(简化形式):

interface IContact extends Document {
  type: string;
  firstName?: string;
}

const contactSchema = new mongoose.Schema({
  contactType: {
    type: String,
    required: true,
    trim: true,
    enum: ['person', 'general']
  },
  firstName: {
    type: String,
    required: function() {
      return this.contactType === 'person';
    },
    minlength: 1,
    trim: true
  }})

 const Contact = mongoose.model<IContact>('Contact', contactSchema);

现在,TypeScript 编译器给了我以下错误:

“Schema |”类型上不存在属性“contactType”模式类型 | SchemaTypeOpts'。 类型“Schema”上不存在属性“contactType”。

是否以这种方式验证必填字段,取自猫鼬文档,正确(使用 this 关键字),还是有其他方法? 或者,我应该以某种方式注释我的 Schema,TypeScript 会知道我的 Schema 中存在 contactType 属性吗?

【问题讨论】:

    标签: node.js mongodb typescript mongoose


    【解决方案1】:

    你可以试试这个,这对我有用:

    // ...contactSchema declaration above... //
    
    contactSchema.obj.firstName.required = function() {
      return this.contactType === 'person';
    };
    
    // ...Contact model declaration below... //
    

    【讨论】:

    • 这里面的obj是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2020-02-05
    相关资源
    最近更新 更多