【问题标题】:Issue with Date and Mongoose Typescript日期和猫鼬打字稿问题
【发布时间】:2021-10-05 15:34:51
【问题描述】:

我正面临着建立 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);

我的问题是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

请告诉我如何解决这个问题。

【问题讨论】:

    标签: node.js typescript mongodb date mongoose


    【解决方案1】:

    Date.now() 是一个返回number 的函数。而不是它,尝试仅使用new Date()。还需要将createdAt的类型更改为Number

    在给定的文档链接中,createdAt 字段类型是 number,但这里你写的是 Date

    interface User {
      name: string;
      email: string;
      avatar?: string;
      createdAt: number;
    }
    

    createdAtupdatedAt 是可以直接使用的时间戳,无需在架构中指定。

    const schema = new Schema<IUser, Model<IUser>, IUser>({
      name: { type: String, required: true },
      email: String,
      avatar: String
    },{
        timestamps: true
    });
    

    【讨论】:

    • 啊,是的。我正在尝试将created 更改为数字但没有运气。在您的帮助下,我找到了解决方案,将模式中的类型更改为数字而不是日期
    • @ĐặngKiên 如果您在架构中使用时间戳选项自动设置它,那就更好了。最好不要更改字段名称。
    • @ĐặngKiên 对于 JS,number 但对于架构,它将是 Number。请考虑接受我的回答。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-04-11
    • 2017-01-20
    • 2016-02-05
    • 2020-05-11
    • 2016-04-01
    • 2021-01-05
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多