node.js - 每次创建文章并将其保存在数据库中时,如何生成 slug?
问题描述
所以,我有这篇文章架构,我想在其中创建一个独特的 slug。
const mongoose = require("mongoose")
const Schema = mongoose.Schema
var URLSlug = require('mongoose-slug-generator')
const articleSchema = new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
userId: { type: Schema.Types.ObjectId, ref: "User" },
slug: { type: "String", slug: "title", unique: true }
}, { timestamps: true })
articleSchema.pre("save", function(next) {
this.slug = this.title.split(" ").join("-")
next()
})
articleSchema.plugin(URLSlug("title", {field: "Slug"}))
const Article = mongoose.model("Article", articleSchema)
module.exports = Article
这是文章控制器
newArticle: (req, res) => {
Article.create(req.body, (err, newArticle) => {
if (err) {
return res.status(404).json({ error: "No article found" })
} else {
return res.status(200).json({ article: newArticle })
}
})
}
我不知道,当我在邮递员中检查时,它说没有找到文章,更不用说蛞蝓了!另外,我收到此错误:
schema.eachPath is not a function
解决方案
根据mongoose-slug-generator您需要在 mongoose 上应用插件,但在您的代码中它被应用到模式。
因此,如果您尝试使用此代码,它将起作用:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var URLSlug = require("mongoose-slug-generator");
mongoose.plugin(URLSlug);
const articleSchema = new Schema(
{
title: { type: String, required: true },
description: { type: String, required: true },
userId: { type: Schema.Types.ObjectId, ref: "User" },
slug: { type: String, slug: "title"}
},
{ timestamps: true }
);
articleSchema.pre("save", function(next) {
this.slug = this.title.split(" ").join("-");
next();
});
const Article = mongoose.model("Article", articleSchema);
module.exports = Article;
如果我们像这样发送 req.body :
{
"title": "metal head dev",
"userId": "5e20954dc6e29d1b182761c9",
"description": "description"
}
保存的文档将是这样的(如您所见 slug 已正确生成):
{
"_id": "5e23378672f10f0dc01cae39",
"title": "metal head dev",
"description": "description",
"createdAt": "2020-01-18T16:51:18.445Z",
"updatedAt": "2020-01-18T16:51:18.445Z",
"slug": "metal-head-dev",
"__v": 0
}
顺便说一句mongoose-slug-generator
,似乎很老了,有一个更流行且维护良好的slugify包。
推荐阅读
- python - VS 代码 - urllib.error.URLError:
- json - 在 bat 文件中解析 JSON
- javascript - 如何在javascript代码中访问从服务器发送的数据(使用flask)?
- uml - 需要帮助创建用例图
- reactjs - 当 eslint 指责 max-length 并且 .prettierignore 不起作用时 Prettier 不适用
- go - go 模块可以没有 go.mod 文件吗?
- solidity - 如何在合同扫描页面中显示网站?
- numbers - 使用 Visual Studio 和 conda 环境的交互式窗口中未显示编辑窗口的行号
- scala - ReactiveMongo 0.20.12-Play28 在启动时因 MatchError 崩溃:成功异常
- javascript - 无法将反应组件导入 gatsby 启动组件