简体   繁体   English

具有 typescript 的节点 js:定义接口时 mongoose 架构日期类型属性出错

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

I have a mongoose schema that looks like this:我有一个看起来像这样的 mongoose 架构:

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.当我向其添加“默认”属性时,我在 created at 属性中遇到类型错误。 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. createdAt 的类型是 DateConstructor , Date.now() 的返回类型是一个数字。 How can I resolve this problem?我该如何解决这个问题?

You can use the built-in timestamps option for your Schema.It will automatically add createdAt field to your schema.您可以为您的架构使用内置的时间戳选项。它会自动将 createdAt 字段添加到您的架构中。 link关联

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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