使用带有打字稿的猫鼬创建自定义验证时出错

Nic*_*lli 5 javascript mongoose mongodb typescript

 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;
        }
      }
    });
Run Code Online (Sandbox Code Playgroud)

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

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

Mat*_*hen 6

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

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;
       }
     }
   });
Run Code Online (Sandbox Code Playgroud)