【问题标题】:Type 'Object' does not satisfy the constraint 'Document'类型“对象”不满足约束“文档”
【发布时间】:2021-01-22 13:30:57
【问题描述】:

我正在尝试运行 MERN 应用程序来验证它有什么,但它在几个文件中向我发送了这个错误。

错误:类型“CatalogType”不满足约束“文档”。 “CatalogType”类型缺少“Document”类型中的以下属性:$ignore、$isDefault、$isDeleted、$isEmpty 和 45 个以上。ts(2344)

我的代码:

const {
      Types: { ObjectId },
    } = Schema;
    
    export interface CatalogType {
      _id: any;
      code: string;
      description: string;
      version: number;
    }
    
export interface CatalogDocumentType extends Document,CatalogType{
      _id: number;
    }
    
export const schema = new Schema<CatalogType>(
      {
        id: {
          type: ObjectId,
        },
        code: {
          type: String,
          required: true,
        },
        description: {
          type: String,
          required: false,
        },
        version: {
          type: Number,
          required: false,
        },
      },
      {
        timestamps: {
          currentTime: () => new TimeZone().getLocaleCSTfromGMT(),
        },
      },
    );
    
export const Model = model<CatalogDocumentType>('Catalog', schema);

请帮帮我!

【问题讨论】:

    标签: node.js mongodb typescript express mongoose


    【解决方案1】:

    泛型类Schema的泛型参数有泛型约束,见index.d.ts

    class Schema<DocType extends Document = Document, M extends Model<DocType> = Model<DocType>> extends events.EventEmitter {/**..*/}
    

    泛型参数DocType 必须满足Document 类型约束。所以正确的做法是:

    import { Schema, model, Document, Model } from 'mongoose';
    
    const {
      Types: { ObjectId },
    } = Schema;
    
    export interface CatalogTypeDocument extends Document {
      _id: number;
      code: string;
      description: string;
      version: number;
    }
    
    export interface CatalogTypeModel extends Model<CatalogTypeDocument> {}
    
    export const schema = new Schema<CatalogTypeDocument>({
      id: {
        type: ObjectId,
      },
      code: {
        type: String,
        required: true,
      },
      description: {
        type: String,
        required: false,
      },
      version: {
        type: Number,
        required: false,
      },
    });
    
    export const CatalogTypeModel = model<CatalogTypeDocument, CatalogTypeModel>('Catalog', schema);
    

    欲了解更多信息,请参阅mongoosejs-typescript-docs

    软件包版本:

    "mongoose": "^5.11.9",
    "@types/mongoose": "^5.10.3",
    "typescript": "^3.7.2"
    

    【讨论】:

      猜你喜欢
      • 2021-01-28
      • 2021-05-13
      • 2019-09-19
      • 1970-01-01
      • 2015-04-01
      • 2020-10-25
      • 2021-04-15
      • 2018-10-16
      • 2020-07-07
      相关资源
      最近更新 更多