Me enfrento al problema con el documento oficial de Mongoose encontrado aquí .
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); Mi problema es que el tipo created en IUser no es el mismo que en el schema y obtuve el error:
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 ... | undefinedPor favor hazme saber como arreglar esto.
Date.now() es una función que devuelve number . En lugar de eso, intente usar new Date() solamente. También es necesario realizar cambios en el tipo de createdAt to Number .
En el enlace del documento dado, el tipo de campo createdAt es number , pero aquí ha escrito Date .
interface User { name: string; email: string; avatar?: string; createdAt: number; }O
createdAt y updatedAt son marcas de tiempo que se pueden usar directamente sin especificar en el esquema.
const schema = new Schema<IUser, Model<IUser>, IUser>({ name: { type: String, required: true }, email: String, avatar: String },{ timestamps: true });