1

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

1 Answers1

0

Your code is correct, replace the arrow function with the regular function because "this" doesn't work with arrow functions and remove required: true from slug field.

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

  next();
});
Imad_k
  • 11
  • 3