简体   繁体   中英

Error in creating a custom validation using mongoose with 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;
        }
      }
    });

The two errors that I get when I run this code are:

  • Property 'bacon' does not exist on type '{ type: StringConstructor; enum: string[]; required: () => any; }'
  • 'required' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.

In order to type-check the required function, TypeScript needs to know what type of object this will refer to when required is called. By default, TypeScript guesses (incorrectly) that required will be called as a method of the containing object literal. Since Mongoose will actually call required with this set to a document of the structure you're defining, you'll need to define a TypeScript interface for that document type (if you don't already have one) and then specify a this parameter to the required function.

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

In my tscongig.json file inside compilerOptions , I changed the following and it worked:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM