Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 277
Niccolò Caselli Avatar asked Oct 23 '18 12:10

Niccolò Caselli


People also ask

Is mongoose validation customizable?

Validation is an important part of the mongoose schema. Along with built-in validators, mongoose also provides the option of creating custom validations. Creating custom validations is also very simple. Custom validations can be used where built-in validators do not fulfill the requirements.

Does mongoose work with TypeScript?

To get started with Mongoose in TypeScript, you need to: Create an interface representing a document in MongoDB. Create a Schema corresponding to the document interface. Create a Model.

What is mongoose error?

MongooseError : general Mongoose error. CastError : Mongoose could not convert a value to the type defined in the schema path. May be in a ValidationError class' errors property.

Does mongoose have built-in validation?

Mongoose has several built-in validators. All SchemaTypes have the built-in required validator. The required validator uses the SchemaType's checkRequired() function to determine if the value satisfies the required validator. Numbers have min and max validators.


1 Answers

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;
       }
     }
   });
like image 140
Matt McCutchen Avatar answered Oct 19 '22 20:10

Matt McCutchen