'validation failed: slug: Path `slug` is required

I created a Blog and for its slug, I install slugify and require it. I'm trying to save a new blog post in MongoDB with mongoose, but I am getting this error: slug: ValidatorError: Path slug is required.

I validate slugify from the tutorial from Web Dev Simplified Youtube Channel but it is not working.

Here is the code :

// getting-started.js
const mongoose = require("mongoose");
const slugify = require("slugify");

main().catch((err) => console.log(err));

async function main() {
  await mongoose.connect(process.env.ATLAS);
}

// Schema
const blogSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    unique: true,
  },
  description: {
    type: String,
    required: true,
  },
  slug: {
    type: String,
    required: true,
    unique: true,
  },
});

blogSchema.pre("validate", (next) => {
  if (this.title) {
    this.slug = slugify(this.title, { lower: true, strict: true });
  }

  next();
});

//   Model
const Blog = mongoose.model("Blog", blogSchema);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source