I have the following Mongoose model schema. I am using the typescript file.
// 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);
I am getting the following error
any Property 'slug' does not exist on type 'Document'.ts(2339)
any Property 'name' does not exist on type 'Document'.ts(2339)
Do you have interface created for your schema?
I would do something like this:
export interface ICategory extends mongoose.Document {
name: string;
slug: string;
description: string;
}
And then you can do something like this:
CategorySchema.pre<ICategory>("save", function(next) {
this.slug = slugify(this.name, { lower: true });
next();
});
That should work.