TypeScript: свойство 'slug' не существует для типа 'Document' - PullRequest
0 голосов
/ 10 ноября 2019

У меня есть следующая схема модели 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' не существует в типе 'Document'.ts (2339)

любое свойство 'name' не существует в типе 'Document'.ts (2339)

1 Ответ

1 голос
/ 14 ноября 2019

У вас есть интерфейс, созданный для вашей схемы?

Я бы сделал что-то вроде этого:

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

Это должно сработать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...