【问题标题】:TypeScript: Property 'slug' does not exist on type 'Document'TypeScript:“文档”类型上不存在属性“slug”
【发布时间】:2020-03-06 12:51:34
【问题描述】:

我有以下 Mongoose 模型架构。我正在使用打字稿文件。

// Core Modules

// NPM Modules
import mongoose from "mongoose";
import slugify from "slugify";

// Custom Modules
const CategorySchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "Please add a Category Name"],
    unique: true,
    trim: true
  },
  slug: {
    type: String,
    unique: true
  },
  description: {
    type: String,
    required: [true, "Please add a description"],
    maxlength: [500, "Description can not be more than 500 characters"]
  }
});

// Create bootcamp slug from the name
CategorySchema.pre("save", function(next) {
  this.slug = slugify(this.name, { lower: true });
  next();
});

module.exports = mongoose.model("Category", CategorySchema);

我收到以下错误

“文档”类型上不存在任何属性“slug”.ts(2339)

“文档”类型上不存在任何属性“名称”.ts(2339)

【问题讨论】:

    标签: typescript mongoose mongoose-schema


    【解决方案1】:

    您是否为您的架构创建了接口?

    我会这样做:

    export interface ICategory extends mongoose.Document {
    name: string;
    slug: string;
    description: string;
    }
    

    然后你可以这样做:

    CategorySchema.pre<ICategory>("save", function(next) {
      this.slug = slugify(this.name, { lower: true });
      next();
    });
    

    应该可以的。

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2018-08-17
      • 1970-01-01
      • 2023-02-06
      • 2021-05-29
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      相关资源
      最近更新 更多