Search code examples
mongooseclass-validatortypescript-classtypegoose

class-validator fails validation for IsDateString with 'must be ISOString but value logged is clearly an ISO String?


The exact error:

    "value": "2019-10-09T10:36:40.791Z",
    "property": "createdAt",
    "children": [],
    "constraints": {
      "isDateString": "createdAt must be a ISOString"
    }

The field in the class:

    @prop({ default: new Date(Date.now()) })
    @IsDefined()
    @IsDateString()
    createdAt: Date;

getting the document coming from the db:

 const order = await this.order.findOne({
      _id: body._id,
      clientId: user.clientId,
    });

calling the validator:

      let orderData = order.toJSON();
      let finalOrder = plainToClass(FinishedOrder, orderData);
      let validation = await validateOrReject(finalOrder);

I've also tried to call order.toObject() but it has the same effect.


Solution

  • What's being logged in the error is not the object itself and turns out that mongoose will convert the date strings to date objects. I ended up making the check on that property optional if the value is a date.