![](/img/trans.png)
[英]Mongoose Schema type as a custom interface from TypeScript?
[英]Node js with typescript: Error in mongoose schema date type property when defining an interface
我有一個看起來像這樣的 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);
還有一個我要添加到架構中的接口:
interface ITour extends mongoose.Document{
name: string;
price: number;
description: string;
createdAt: Date;
startDates: Date[];
}
當我向其添加“默認”屬性時,我在 created at 屬性中遇到類型錯誤。 當我刪除默認屬性時,一切正常。 createdAt 的類型是 DateConstructor , Date.now() 的返回類型是一個數字。 我該如何解決這個問題?
您可以為您的架構使用內置的時間戳選項。它會自動將 createdAt 字段添加到您的架構中。 關聯
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.