【问题标题】:How to create a custom schema type with typescript for mongoose如何使用打字稿为猫鼬创建自定义模式类型
【发布时间】:2018-12-28 05:55:10
【问题描述】:

我正在设置一个示意图类型,以了解它如何与 typescript 和 mongoose 一起使用。该示例使用简单的正则表达式验证电子邮件,但我不知道如何注入 mongoose.d.ts 的声明

这是怎么工作的?

email.ts

import * as mongoose from 'mongoose'

function Email (path: any, options: any[]) {
  mongoose.SchemaType.call(this, path, options, 'Email')
}

Email.prototype = Object.create(mongoose.SchemaType.prototype)

Email.prototype.cast = function (email: string) {
  if (!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)) {
    throw new Error('Invalid email address')
  }
  return email
}

// Typescript: Property 'Email' does not exist on type 'typeof Types'.
mongoose.Schema.Types.Email = Email

email.d.ts

declare module 'mongoose' {
  namespace Schema {
    namespace Types {
      // ???
    }
  }
}

我想在方案中得到这个结果

const schema: mongoose.Schema = new mongoose.Schema({
  email: {
    type: Email
  }
})

【问题讨论】:

  • 如果您“按原样”使用它,您真的需要将新类型添加到mongoose.Schema.Types 中吗?如果我只是将您对Email 的定义和您的方案(除了“隐式this”之外),TS 没有抛出任何错误。
  • ts没有播放错误,我需要挂载不同类型的pos,将在几个不同的模型中使用:(

标签: typescript mongoose


【解决方案1】:

我终于做到了,我做了一个功能,但我认为我可以改进! :)

index.d.ts

declare module 'mongoose' {
  namespace Schema {
    namespace Types {
      function Email (path: string, options: any): void
    }
  }
}

email.ts

import * as mongoose from 'mongoose'

function Email (path: string, options: any): void {
  mongoose.SchemaTypes.String.call(this, path, options)

  function isValid (val) {
    // validation logic
  }

  this.validate(isValid, options.message || 'invalid email address')
}

Object.setPrototypeOf(Email.prototype, mongoose.SchemaTypes.String.prototype)

mongoose.Types.Email = Email
mongoose.SchemaTypes.Email = Email

【讨论】:

    【解决方案2】:

    email.ts

    import mongoose from 'mongoose';
    
    export default class Email extends mongoose.SchemaType {
        cast(email: string) {
            if (!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)) {
                throw new Error('Invalid email address')
            }
            return email
        }
    }
    
    mongoose.Schema.Types.Email = Email;
    

    index.d.ts

    declare module 'mongoose' {
        namespace Schema {
            namespace Types {
                class Email extends SchemaType {}
            }
        }
    }
    

    【讨论】:

    • 您的代码看起来不错,但您在哪里找到该正则表达式? many of them 的工作方式不同,并且与相同的电子邮件不匹配
    • @NinoFiliu,我明白你的意思,但我只是重复了问题中使用的验证。我的意思是展示一种简单而有风格的方式来向 mongoose 添加新的模式类型。
    • 我的错,我没有看到 OP 使用了相同的正则表达式!那好吧。
    猜你喜欢
    • 2017-06-30
    • 2014-02-15
    • 2018-08-20
    • 2022-01-08
    • 2019-03-22
    • 2013-09-22
    • 2017-01-20
    • 2020-10-29
    • 2018-10-09
    相关资源
    最近更新 更多