【问题标题】:Error in creating a custom validation using mongoose with typescript使用带有打字稿的猫鼬创建自定义验证时出错
【发布时间】:2019-03-27 16:08:15
【问题描述】:
 import mongoose, { Schema, model } from "mongoose";

 var breakfastSchema = new Schema({
      eggs: {
        type: Number,
        min: [6, "Too few eggs"],
        max: 12
      },
      bacon: {
        type: Number,
        required: [true, "Why no bacon?"]
      },
      drink: {
        type: String,
        enum: ["Coffee", "Tea"],
        required: function() {
          return this.bacon > 3;
        }
      }
    });

我在运行此代码时遇到的两个错误是:

  • 类型 '{ type: StringConstructor; 上不存在属性 'bacon' 枚举:字符串[];必需:() => 任何; }'
  • “required”隐含返回类型“any”,因为它没有返回类型注释,并且在其返回表达式之一中直接或间接引用。

【问题讨论】:

    标签: javascript mongodb typescript mongoose


    【解决方案1】:

    为了对required 函数进行类型检查,TypeScript 需要知道在调用requiredthis 将引用什么类型的对象。默认情况下,TypeScript 猜测(错误地)required 将作为包含对象字面量的方法被调用。由于 Mongoose 实际上会调用 required 并将 this 设置为您正在定义的结构的文档,因此您需要为该文档类型定义一个 TypeScript 接口(如果您还没有),然后指定required 函数的 this 参数。

    interface Breakfast {
        eggs?: number;
        bacon: number;
        drink?: "Coffee" | "Tea";
    }
    
    var breakfastSchema = new Schema({
         eggs: {
           type: Number,
           min: [6, "Too few eggs"],
           max: 12
         },
         bacon: {
           type: Number,
           required: [true, "Why no bacon?"]
         },
         drink: {
           type: String,
           enum: ["Coffee", "Tea"],
           required: function(this: Breakfast) {
             return this.bacon > 3;
           }
         }
       });
    

    【讨论】:

    • 非常感谢@Matt McCutchen。我想知道是否可以通过创建类型而不是接口来解决问题,因为但是正如文档所说我必须定义一个类型,因此首先在猫鼬方案中定义相同的模式似乎非常夸张,然后作为接口,最后作为类型。export type UserModel = mongoose.Document & { email: string, name: string }; const userSchema = new mongoose.Schema({ email: { type: String, unique: true }, name{ type: String, unique: true }, });
    • 是的,您可能可以使用 UserModel 类型。传递给required 函数的this 对象是否具有内置的mongoose.Document 属性以及特定于您的架构的属性是一个问题。我猜它确实如此,但你总是可以测试它。
    【解决方案2】:

    compilerOptions 内的tscongig.json 文件中,我更改了以下内容并且它起作用了:

    "noImplicitThis": false, 
    ...
    /* Raise error on 'this' expressions with an implied 'any' type. */
    

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 2021-01-05
      • 1970-01-01
      • 2017-06-30
      • 2016-06-14
      • 2014-07-08
      • 2018-08-20
      • 2018-10-24
      相关资源
      最近更新 更多