javascript - 使用带 typescript 的 Mongoose 创建自定义验证时出错

标签 javascript mongodb typescript mongoose

 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;
        }
      }
    });

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

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

最佳答案

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

关于javascript - 使用带 typescript 的 Mongoose 创建自定义验证时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52948723/

相关文章:

javascript - Semantic-UI 图像属性不适用于语义-ui-react

javascript - 格式化 Json 文件中的 Json 对象值

javascript - Limit = 1 = 1ms, Limit > 1 = 150ms (mongo-melt-down)

typescript - 如何在 TypeScript 中映射类型并添加基于 this 的类型防护?

typescript - 在 typescript 中获取枚举键作为联合字符串的通用类型?

javascript - 按一个属性对 javascript 项目进行分组

javascript原型(prototype)方法未定义

mongodb - mongodb中$where查询中两个不同字段的逻辑或

javascript - 从 sails.js/mongodb 中提取公共(public)代码

Angular 6 : HttpErrorResponse SyntaxError: Unexpected token s in JSON