我创建了一个Blog,对于它的插件,我安装了slugify并需要它。我试图保存一个新的博客文章MongoDB与猫鼬,但我得到这个错误:slug: ValidatorError: Path slug is required.
我从Web Dev Simplified Youtube Channel的教程中验证了slugify,但它不起作用。
代码如下:
// 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);
你的代码是正确的,用常规函数替换箭头函数,因为"this"不能使用箭头函数,remove required: true
blogSchema.pre("validate", function (next) {
if (this.title) {
this.slug = slugify(this.title, { lower: true, strict: true });
}
next();
});