Search code examples
node.jstypescriptmongoose-schema

Node js with typescript: Error in mongoose schema date type property when defining an interface


I have a mongoose schema that looks like this:

import mongoose from 'mongoose';
const { Schema } = mongoose;

const tourSchema = new Schema<ITour>({
  name: String,    
  price: {
    type: Number,
    default: 0,
  },
  description: {
    type: String,
    trim: true,
  },
  createdAt: {
    type: Date,
    default: Date.now(),
    select: false,
  },
  startDates: [Date],
});

export const Tour = mongoose.model("Tour", tourSchema);

And an interface That i'm adding to the schema:

interface ITour extends mongoose.Document{
  name: string;
  price: number;
  description: string;
  createdAt: Date;
  startDates: Date[];
}

I'm getting the a type error in the created at property when i'm adding the "default" property to it. When i'm removing the default property everything is working. The type of the createdAt is DateConstructor and the return type of Date.now() is a number. How can I resolve this problem?


Solution

  • You can use the built-in timestamps option for your Schema.It will automatically add createdAt field to your schema. link

    const tourSchema = new Schema<ITour>({
      name: String,    
      price: {
        type: Number,
        default: 0,
      },
      description: {
        type: String,
        trim: true,
      },
      {
        timestamps: true
      },
      startDates: [Date],
    });