打字稿:属性 'slug' 在类型 'Document' 上不存在

TypeScript: Property 'slug' does not exist on type 'Document'

我有以下 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);

我收到以下错误

any Property 'slug' does not exist on type 'Document'.ts(2339)

any Property 'name' does not exist on type 'Document'.ts(2339)

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

我会这样做:

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();
});

应该可以。