【问题标题】:Mongoose + Typescript requires me to extend DocumentMongoose + Typescript 需要我扩展 Document
【发布时间】:2021-08-20 01:51:54
【问题描述】:

我正在尝试按照 Mongoose 文档中给出的说明来支持 TypeScript:https://mongoosejs.com/docs/typescript.html

在文档中,他们提供了以下示例:

import { Schema, model, connect } from 'mongoose';

// 1. Create an interface representing a document in MongoDB.
interface User {
  name: string;
  email: string;
  avatar?: string;
}

// 2. Create a Schema corresponding to the document interface.
const schema = new Schema<User>({
  name: { type: String, required: true },
  email: { type: String, required: true },
  avatar: String
});

// 3. Create a Model.
const UserModel = model<User>('User', schema);

他们还提供了接口扩展 Document 的替代示例:

interface User extends Document {
  name: string;
  email: string;
  avatar?: string;
}

他们建议不要使用扩展Document 的方法。但是,当我尝试他们的确切代码(没有extends)时,我收到以下错误:

Type 'User' does not satisfy the constraint 'Document<any, {}>'.
  Type 'User' is missing the following properties from type 'Document<any, {}>': $getAllSubdocs, $ignore, $isDefault, $isDeleted, and 47 more.

我正在使用 Mongoose v 5.12.7。有什么我不明白的吗?如何在不扩展文档的情况下创建架构?我想稍后对其进行测试,并且我不想模拟 47 个或更多属性...

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    好的,我想通了。我有两个问题。首先,我使用的是第三方 @types/mongoose 包,由于 Mongoose 原生支持 TypeScript,因此不再需要它。

    但是,主要问题实际上是版本。尽管在文档中说新的支持从 v5.11.0 开始就存在,但我安装的 v5.12.7 和当前版本 5.12.12 之间的区别实际上很重要。一旦我更新了版本,所有的错误都消失了。

    【讨论】:

      【解决方案2】:

      删除 @types/mongoose 并更新 mongoose 对我有用。你不需要@types/mongoose 因为猫鼬支持打字稿从5.11.0版开始

      删除@types/mongoose:

      yarn remove @types/mongoose
      

      更新猫鼬:

      yarn update mongoose
      

      【讨论】:

        猜你喜欢
        • 2015-06-21
        • 2017-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多