[英]Issue with Date and Mongoose Typescript
I'm facing the issue with the Mongoose official document founded here .我正面临 Mongoose 官方文档的问题。
import { Schema, Model, model } from 'mongoose';
export interface IUser {
name: string;
email: string;
avatar?: string;
created: Date;
}
const schema = new Schema<IUser, Model<IUser>, IUser>({
name: { type: String, required: true },
email: String,
avatar: String,
created: { type: Date, default: Date.now },
});
export const UserModel = model<IUser>('User', schema);
My problem is the created
type in IUser
is not the same as in schema
and got the error:我的问题是IUser
中created
的类型与schema
中的不同并且出现错误:
Type '{ type: DateConstructor; default: () => number; }' is not assignable to type 'typeof SchemaType | Schema<any, any, undefined, unknown> | Schema<any, any, undefined, unknown>[] | readonly Schema<any, any, undefined, unknown>[] | Function[] | ... 6 more ... | undefined'.
Types of property 'type' are incompatible.
Type 'DateConstructor' is not assignable to type 'Date | typeof SchemaType | Schema<any, any, undefined, unknown> | undefined'.
Type 'DateConstructor' is missing the following properties from type 'typeof SchemaType': cast, checkRequired, set, getts(2322)
(property) created?: typeof SchemaType | Schema<any, any, undefined, unknown> | Schema<any, any, undefined, unknown>[] | readonly Schema<any, any, undefined, unknown>[] | Function[] | ... 6 more ... | undefined
Please let me know how to fix this.请让我知道如何解决这个问题。
Date.now()
is a function which returns number
. Date.now()
是一个返回number
的函数。 Instead of it, try using new Date()
only.相反,尝试仅使用new Date()
。 Also need to make changes in the type of createdAt
to Number
.还需要将createdAt
的类型更改为Number
。
In the given doc link, createdAt
field type is number
but here you have written Date
.在给定的 doc 链接中, createdAt
字段类型是number
但在这里你写的是Date
。
interface User {
name: string;
email: string;
avatar?: string;
createdAt: number;
}
OR要么
createdAt
and updatedAt
are timestamps which can be used directly without specifying in the schema. createdAt
和updatedAt
是可直接使用而无需在该模式中指定时间戳。
const schema = new Schema<IUser, Model<IUser>, IUser>({
name: { type: String, required: true },
email: String,
avatar: String
},{
timestamps: true
});
I think this is working我认为这是有效的
import { Schema,Document } from 'mongoose';
export interface IUser {
name: string;
email: string;
avatar?: string;
created: Date;
}
const schema = new Schema<IUser>({
name: { type: String, required: true },
email: String,
avatar: String,
created: { type: Date, default: Date.now },
}); });
export const UserModel = model<IUser>('User', schema);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.